我的页面顶部有一个简单的菜单栏。我想点击一个元素并具有反色/背景色。显然,我需要能够在更改单击元素上的样式之前将所有兄弟元素重置为默认颜色/背景颜色。
到目前为止,我的点击事件功能看起来像这样
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中有没有更好的方法或更“棱角分明”的方式或更清洁的方式来实现这一目标?
这就是我现在正在尝试的但是该课程没有从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;
}
答案 0 :(得分:2)
您可以尝试这样的事情:
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;
}
}
答案 1 :(得分:1)
这样做的有条理的方法是:
is ==
获取正确的课程