【问题标题】:Toggle Class to only one button in angular 4将类切换到角度 4 中的一个按钮
【发布时间】:2018-08-03 10:37:41
【问题描述】:

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

【问题讨论】:

  • 这样做的目的是什么?
  • 我的一个项目想要这种功能

标签: html css angular angular5 angular4-forms


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      应用组件

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

      【讨论】:

        猜你喜欢
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-22
        • 2020-08-24
        相关资源
        最近更新 更多