我试图仅将CSS类应用于单击的按钮(将其设置为活动状态)。
这是我的代码:
filter.component.html
<div class="button-container">
<button class="rules" [class.active]="active" (click)="toggleActive()" type="button">Rules</button>
<button class="dailies" [class.active]="active" (click)="toggleActive()" type="button">Dailies</button>
<button class="emotions" [class.active]="active" (click)="toggleActive()" type="button">Emotions</button>
</div>
filter.component.ts
export class FilterComponent {
active: boolean = false;
toggleActive(): void {
this.active = !this.active;
}
constructor() {}
}
我的问题是,该类适用于所有3个按钮。每个按钮上的活动类看起来都不同。我该如何解决这个问题?
答案 0 :(得分:4)
你可以这样做:
模板方:
<div class="button-container">
<button class="rules" [class.active]="active.rules" (click)="toggleActive('rules')" type="button">Rules</button>
<button class="dailies" [class.active]="active.dailies" (click)="toggleActive('dailies')" type="button">Dailies</button>
<button class="emotions" [class.active]="active.emotions" (click)="toggleActive('emotions')" type="button">Emotions</button>
</div>
组件方:
active = {};
toggleActive(el): void {
this.active[el] = this.active[el] ? false : true;
}
<强> WORKING DEMO 强>
答案 1 :(得分:0)
尝试使用事件获取当前单击的元素,如下所示:
toggleActive($event) {
var element = $event.target;
element.active = !element.active;
};