Anamik Adhikary
Anamik Adhikary

Reputation: 451

Add CSS based on Button Activated Ionic/Angular 8

I have buttons which are dynamically generated. On click of any one of the buttons, I want the css of the button to be changed, based on which button is activated.

My code:

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

The CSS flashes for a second and then goes away.

How can I make the CSS be there if the button is activated.

Upvotes: 0

Views: 746

Answers (1)

Najam Us Saqib
Najam Us Saqib

Reputation: 3404

you can use Index as your selected button:

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

Upvotes: 3

Related Questions