添加 CSS 基于激活的按钮 Ionic/Angular 8

Add CSS based on Button Activated Ionic/Angular 8

我有动态生成的按钮。单击任一按钮时,我希望根据激活的按钮更改按钮的 css。

我的代码:

HTML:

 <div class="container">
<div class="scroll" scrollX="true">
  <span *ngFor="let item of buttons; let i = index" (click)="genreSelect(item)"
    ><ion-button shape="round" [ngClass]="{activated: buttonActive}">{{item.catName}}</ion-button></span
  >
</div>

TS:

this.buttons = [{
      id: 1,
      catName:'Electronics'
    },{
      id: 2,
      catName:'Books'
    },{
      id: 3,
      catName:'Furniture'
    },{
      id: 4,
      catName:'Laptops'
    }];




genreSelect(item){
    console.log(item);
    
    this.buttonActive = true;
  }

CSS:

.activated:active{
    background-color: red;
  }

CSS 闪烁一秒钟然后消失。

如果按钮被激活,我怎样才能使 CSS 在那里。

您可以使用 Index 作为您选择的按钮:

<div class="container">
   <div class="scroll" scrollX="true">
      <span *ngFor="let item of buttons; let i = index (click)="genreSelect(item, i)">
         <ion-button shape="round" [ngClass]="activeIndex == i ? 'buttonActive': ''"> 
            {{item.catName}}
         </ion-button>
      </span>
   </div>
</div>

.ts:

activeIndex = null;

genreSelect(item, index){
   this.activeIndex = index;
}