Angular - 使按钮在单击时处于活动状态,在单击组中的其他按钮时处于非活动状态
Angular - Make a button active when it is clicked and inactive when an other button in the group is clicked
我从这个 post 得到了这段代码
我正在尝试做的是 post 中提到的同一件事,在单击按钮时激活按钮并使组中的其他按钮处于非活动状态。
复制了相同的代码,由于某种原因它不起作用
<button mat-button *ngFor="let button of filterButtons" [ngClass]="{'active': button.isClicked}" (click)="button.isClicked = !button.isClicked">
{{ button.text }}
</button>
Component.ts
filterButtons = [
{ text: 'Posted', isClicked: false },
{ text: 'FFM', isClicked: false },
{ text: '9999', isClicked: false },
{ text: '9000', isClicked: false },
{ text: '8555', isClicked: false },
{ text: 'Canceled', isClicked: false },
]
问题是您在单击其他按钮时没有重置 isClicked 值。
最简单的解决方案是这样的。
app.component.html
<button mat-button *ngFor="let button of filterButtons" [ngClass]="{'active': button.isClicked}" (click)="setActive(button)">
{{ button.text }}
</button>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
filterButtons = [
{ text: 'Posted', isClicked: false },
{ text: 'FFM', isClicked: false },
{ text: '9999', isClicked: false },
]
setActive(button: any): void {
for(let but of this.filterButtons) {
but.isClicked = false;
}
button.isClicked = true;
}
}
您可以找到其他解决方案,如
中所述
我从这个 post
<button mat-button *ngFor="let button of filterButtons" [ngClass]="{'active': button.isClicked}" (click)="button.isClicked = !button.isClicked">
{{ button.text }}
</button>
Component.ts
filterButtons = [
{ text: 'Posted', isClicked: false },
{ text: 'FFM', isClicked: false },
{ text: '9999', isClicked: false },
{ text: '9000', isClicked: false },
{ text: '8555', isClicked: false },
{ text: 'Canceled', isClicked: false },
]
问题是您在单击其他按钮时没有重置 isClicked 值。
最简单的解决方案是这样的。
app.component.html
<button mat-button *ngFor="let button of filterButtons" [ngClass]="{'active': button.isClicked}" (click)="setActive(button)">
{{ button.text }}
</button>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
filterButtons = [
{ text: 'Posted', isClicked: false },
{ text: 'FFM', isClicked: false },
{ text: '9999', isClicked: false },
]
setActive(button: any): void {
for(let but of this.filterButtons) {
but.isClicked = false;
}
button.isClicked = true;
}
}
您可以找到其他解决方案,如