我的页面顶部有一个简单的菜单栏。我想单击一个元素并使用反色/背景色。显然,在更改单击元素的样式之前,我需要能够将所有同级元素重置为默认颜色/背景颜色。
到目前为止我的点击事件函数是这样的
onSelect(event, source: Source): void {
console.log(event.target);
//reset all a elements do background-color:white and color:white
var siblings = event.target.parentNode.children;
for(var i=0; i<siblings.length; i++) {
siblings[i].style.backgroundColor = "white";
siblings[i].style.color = "black";
}
event.target.style.backgroundColor = "black";
event.target.style.color = "white";
this._sharedService.publishData(source.id);
}
在 Angular 2 中是否有更好的方法或更“有 Angular ”的方法或更简洁的方法来实现这一点?
这就是我现在正在尝试的,但是类不会从 unsel-source 更改为 sel-source
我的 source.component.html 文件如下所示:
<nav id="nav" class="fixed sources-main">
<div class="flex flex-wrap pl1 border-bottom">
<a *ngFor="let source of sources; let i = index"
[ngClass]="{'sel-source':isSelected === i}"
(click)="onSelect(i, source)"
class="h5 bold mr1">
{{source.name}}
</a>
</div>
</nav>
source.component.ts 文件如下所示:
import { Component, OnInit } from '@angular/core';
import {SourcesService} from './sources.service'
import { Source } from './source';
import { SharedService } from '../shared.service';
@Component({
selector: 'app-sources',
templateUrl: './sources.component.html',
styleUrls: ['./sources.component.css'],
providers:[SourcesService]
})
export class SourcesComponent implements OnInit {
sources : Source[];
isSelected;
constructor(sourceService: SourcesService, private _sharedService: SharedService) {
sourceService.getSources().subscribe(sources => this.sources = sources);
}
ngOnInit() {
}
onSelect(index, source: Source): void {
this.isSelected = index;
this._sharedService.publishData(source.id);
}
}
我的 styles.css 文件
body, a {
font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Open Sans,Helvetica Neue,Helvetica,sans-serif;
line-height: 1.5;
margin: 0;
color: #111;
background-color: #fff;
}
.sources-main {
width:100%;
background-color: #fff;
}
.articles-main {
padding-top: 25px;
}
.sel-source {
color:white;
background-color: black;
}
你可以尝试这样的事情:
- 当你循环遍历 ngFor 中的元素时,也抓取它的索引
- 当点击事件被触发时,在循环中也传入索引并将其分配给一个变量
- 在跟踪所选索引的组件中有一个属性(它将以未定义开始
- 在点击事件处理程序中,将选中的索引设置为传入的值
- 回到html中,根据索引是否是选择的索引,用ngClass动态设置一个类
import { Component } from '@angular/core';
@Component({
selector: 'test',
template: `
<div
*ngFor="let item of items; let i = index"
[ngClass]="{'selected': selectedItem === i}"
(click)="onItemClick(i)">
{{ item }}
</div>
`,
styles: [`
.selected {
background-color: black;
}
`]
})
export class AppComponent {
selectedItem;
items = ["A", "B", "C", "D", "E", "F", "G", "H"];
onItemClick(index) {
this.selectedItem = index;
}
}
我是一名优秀的程序员,十分优秀!