如何在angular2中单击div时更改div的backgroundcolor

时间:2017-10-18 21:01:22

标签: angular

这里,div是在循环中创建的。我想要第一个div有一个默认的蓝色和休息黑色backgroundcolor。当点击其他div时,div变成蓝色而其他黑色。 怎么做?

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>

1 个答案:

答案 0 :(得分:2)

通常最好在可能的情况下将此状态存储在视图模型(组件)中。您可以尝试这样的事情:

@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];
    }
}