我在页面顶部有一个简单的菜单栏。我想单击一个元素,并具有反颜色/背景色。显然,在更改单击元素上的样式之前,我需要能够将所有兄弟姐妹元素重置回默认的颜色/背景色。
到目前为止,我的点击事件功能看起来像
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中有更好的方法或更"角度"的方法或更清洁的方法?
这是我现在正在尝试的东西,但是班级不会从UNSELCE变为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);
}
}
我的style.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;
}
}
一种角度的做法是:
- 为您的黑色/白色/背景上课
- 使用
ng-class=""
获得正确的类