我有两个按钮,我想切换当前点击的按钮的类。条件是用户一次只能选择一个按钮,用户也可以取消选择两个按钮。这是我的代码stackblitz example。我已经切换了类,但现在我面临的问题是如何取消已选择的按钮。请帮忙。
我有两个按钮,我想切换当前点击的按钮的类。条件是用户一次只能选择一个按钮,用户也可以取消选择两个按钮。这是我的代码stackblitz example。我已经切换了类,但现在我面临的问题是如何取消已选择的按钮。请帮忙。
[
{class: "fa fa-long-arrow-up", name: "button1", selected: false},
{class: "fa fa-long-arrow-down", name: "button2", selected: false},
]
我们需要识别带有id的按钮。请参见*ngFor
。并在单击时调用函数以执行其背后的逻辑。
<button *ngFor="let button of buttons; let i = index" class="btn rounded m-4" [ngClass]="button.selected ? 'btn-primary' : 'btn-default'" (click)="selectButton(i)">
<i [class]="button.class"></i>
</button>
public selectButton(j: number){
this.buttons[j].selected = !this.buttons[j].selected;
for(let i = 0; i < this.buttons.length; i++){
if(i != j){
this.buttons[i].selected = false;
}
}
}
https://stackblitz.com/edit/angular-powyop?file=src/app/app.component.ts
HTML
<button *ngFor="let button of buttons" class="btn rounded m-4" [ngClass]="(selectedButton == button) ? 'btn-primary' : 'btn-default'" (click)="onClickButton(button)">
<i [class]="button.class"></i>
</button>
TS
onClickButton(button): void {
if (this.selectedButton === button) {
this.selectedButton = null;
} else {
this.selectedButton = button;
}
}
<import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
buttons= [
{class: "fa fa-long-arrow-up", name: "button1"},
{class: "fa fa-long-arrow-down", name: "button2"},
]
selectedButton;
buttonNum:number;
clickButton(event,i){
if(this.buttonNum == i){
this.buttonNum = -1;
}else{
this.buttonNum = i;
}
}
}
<button *ngFor="let button of buttons; let i = index" class="btn rounded m-4" [ngClass]="(i == buttonNum) ? 'btn-primary' : 'btn-default'" (click)="clickButton($event,i)">
<i [class]="button.class"></i>
</button>