代码之家  ›  专栏  ›  技术社区  ›  vedankita kumbhar

在角度4中将类切换为仅一个按钮

  •  3
  • vedankita kumbhar  · 技术社区  · 8 年前

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

    3 回复  |  直到 8 年前
        1
  •  3
  •   Malindu Sandaruwan    8 年前

    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
  •  4
  •   Ploppy    8 年前

    您需要将按钮的状态存储在某个地方,我将在按钮数组中执行此操作:

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

        3
  •  0
  •   lakshitha madushan    8 年前

    应用组件

    <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> 
    
    推荐文章