0

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.

5
  • 1
    The :active pseudo class is only applied while the button is pressed. You want to use .activated, .activated:hover, .activated:active { background-color: red; } if you want the background to be red for all button states. Commented Jan 4, 2022 at 15:18
  • With this css of all the buttons get changed. I want only the selected button's css to change Commented Jan 4, 2022 at 15:22
  • Yes, you have all buttons' ngClass bound to the same variable (buttonActive). You need more than one variable. Commented Jan 4, 2022 at 15:23
  • 1
    Since you have buttons as object, you can add key 'active' as boolean and pass bttn id through click event to method which will change 'active' to false on all bttns and set it to true for the clicked bttn, then have ngClass on button return one css in case the button.active and the other css if !button.active Commented Jan 4, 2022 at 16:17
  • 1
    as @MishaMashina said either take a boolean in your JSON objects or you can use Index as selected button to add your css. Commented Jan 4, 2022 at 18:36

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

this works with some small changes in the ngclass [ngClass]="activeIndex === i ? 'buttonActive': ''" The bracket needs to be removed. Else it gives syntax error for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.