将 Class 切换为 angular 中只有一个按钮 4

Toggle Class to only one button in angular 4

我有两个按钮要切换 class 到当前单击的按钮。条件是用户一次只能select一个按钮,用户也可以取消select两个按钮。这是我的代码 stackblitz example。我有切换 class 但现在我面临 deselect selected 按钮的问题。请帮忙。

您需要将按钮的状态存储在某处,我将在按钮数组中进行:

[
  {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;
 }
}

A​​ppComponent

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

}

HTML

<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>