在Angular 4中将"class"属性添加到仅一个按钮

4

我有两个按钮,我想切换当前点击的按钮的类。条件是用户一次只能选择一个按钮,用户也可以取消选择两个按钮。这是我的代码stackblitz example。我已经切换了类,但现在我面临的问题是如何取消已选择的按钮。请帮忙。


这样做的意义是什么呢? - Malindu Sandaruwan
我想在我的一个项目中实现这种功能。 - vedankita kumbhar
3个回答

4
你需要将按钮的状态存储在某个地方,我会将其存储在buttons数组中:
[
  {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>

我们反转点击按钮的状态,并将所有其他按钮关闭。 TS:
 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


4

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接