Search code examples
angularng-class

Apply toggle ngclass to multiple buttons


I'm new to Angular and still trying to get into Angular thinking . I've several buttons like :

    <button class="btn" (click)="btn1()"  [ngClass]="test ? 'Style':'StyleChange'">btn1</button>
   <button class="btn" (click)="btn2()"  [ngClass]="test ? 'StyleChange':'Style'">btn2</button>
  <button (click)="btn3()"  [ngClass]="test? 'Style':'StyleChange'">btn3 </button>

And I'm trying to apply multiple classes through ngClass to have active class only on one button at time. I try to do it in this way but when i click third button ,first button gets the class too. I know that i can use ngFor and will be more easy to achive this but i need to work with every button later.

Component.ts code

test = true;
btn1(){

  this.test = !this.test;
}
btn2(){
 
  this.test = !this.test;
}
btn3(){
 
this.test=!this.test
}

Solution

  • You can create just one variable and change the value every time you click on a button.

    Your component.ts would be in that case:

    test: string = 'test1';
    

    Your html:

    <button class="btn" (click)=" test='test1' " [ngClass]="test === 'test1' ? 'style':'styleChange'">btn1</button>
    <button class="btn" (click)=" test='test2' " [ngClass]="test === 'test2' ? 'style':'styleChange'">btn2</button>
    <button class="btn" (click)=" test='test3' " [ngClass]="test === 'test3' ? 'style':'styleChange'">btn3 </button>
    

    You can create as many buttons as you need and change for every next button just a value.