如何在angular2中单击div时更改div的背景颜色 [英] how to change backgroundcolor of divs when they are clicked in angular2
本文介绍了如何在angular2中单击div时更改div的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此处,div是在循环中创建的.我想让第一个div具有默认的蓝色,其余的为黑色backgroundcolor.单击其他div时,该div会变为蓝色,而其他变为黑色. 该怎么做?
Here, divs are created in a loop. I want first div to have a default blue color and rest black backgroundcolor. when other div are clicked that div become blue and other black. How to do that ?
app.component.ts
------------------------
tabsData = ['a', 'br', 'Sp', 'hh','ee'];
app.component.html
---------------------
<div class="col-xs-12 rmpm tabsMenu" id="navBar">
<div class="">
<div class="navMenu menu-list " (click)="changeClass($event)" *ngFor="let tab of tabsData;let i = index; let frst=first" [ngClass]="{'active': isSelected, 'active': frst}" >
{{tab}}
</div>
</div>
</div>
推荐答案
通常最好在可能的情况下将此状态存储在视图模型(组件)中.您可以尝试这样的事情:
It is often best to store this state in the view model (component) when possible. You might try something like this:
@Component({
selector: 'app-my-component',
template: `
<div class="col-xs-12 rmpm tabsMenu" id="navBar">
<div class="">
<div class="navMenu menu-list"
*ngFor="let tab of tabsData"
(click)="selected = tab"
[class.active]="tab === selected">
{{tab}}
</div>
</div>
</div>
`
})
export class MyComponent implements OnInit {
@Input() public tabsData: Tab[] = [];
public selected: Tab;
public ngOnInit(): void {
this.selected = tabsData[0];
}
}
这篇关于如何在angular2中单击div时更改div的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文