代码之家  ›  专栏  ›  技术社区  ›  Sumchans

角度-单击按钮时使其处于活动状态,单击组中的其他按钮时使其处于非活动状态

  •  0
  • Sumchans  · 技术社区  · 7 年前

    我从这个帖子里得到这个密码 Adding the active class to each clicked button, Angular 4 我所要做的和那篇文章中提到的一样,当一个按钮被点击时激活它,并使组中的其他按钮处于非活动状态。 复制了相同的代码,由于某些原因它不起作用

    <button mat-button *ngFor="let button of filterButtons" [ngClass]="{'active': button.isClicked}" (click)="button.isClicked = !button.isClicked">
        {{ button.text }}
    </button>
    

    组件

      filterButtons = [
        { text: 'Posted', isClicked: false },
        { text: 'FFM', isClicked: false },
        { text: '9999', isClicked: false },
        { text: '9000', isClicked: false },
        { text: '8555', isClicked: false },
        { text: 'Canceled', isClicked: false },
      ]
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   firegloves    7 年前

    问题是,当您单击其他按钮时,您没有重置isclicked值。

    最简单的解决办法就是这样。

    app.component.html软件

    <button mat-button *ngFor="let button of filterButtons" [ngClass]="{'active': button.isClicked}" (click)="setActive(button)">
        {{ button.text }}
    </button>
    

    应用组件

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
        filterButtons = [
        { text: 'Posted', isClicked: false },
        { text: 'FFM', isClicked: false },
        { text: '9999', isClicked: false },
      ]
    
    
      setActive(button: any): void {
        for(let but of this.filterButtons) {
          but.isClicked = false;
        }
    
        button.isClicked = true;
      }
    }
    

    您可以找到其他解决方案,如 this post

    推荐文章