[英]Apply CSS class only to the button that was clicked
I'm trying to apply a CSS class only to the button that was clicked (to set it active). 我正在尝试仅将CSS类应用于单击的按钮(将其设置为活动状态)。
Here's my code: 这是我的代码:
filter.component.html 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 filter.component.ts
export class FilterComponent {
active: boolean = false;
toggleActive(): void {
this.active = !this.active;
}
constructor() {}
}
My problem is, the class gets applied to all 3 buttons. 我的问题是,该类将应用于所有3个按钮。 And the active class looks different on each of the buttons.
并且活动类在每个按钮上看起来都不同。 How can I fix this?
我怎样才能解决这个问题?
You can do it this way : 您可以这样操作:
Template side :
模板端:
<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>
Component side :
组件侧:
active = {};
toggleActive(el): void {
this.active[el] = this.active[el] ? false : true;
}
Try using an event to get the current clicked element as follows: 尝试使用一个事件来获取当前单击的元素,如下所示:
toggleActive($event) {
var element = $event.target;
element.active = !element.active;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.