Home > Software engineering >  How can I add or remove class name in Angular?
How can I add or remove class name in Angular?

Time:12-22

I want to add desActive class name when I press the button. And also remove when I press other button.

Exp. : Site opening class desc2 named has desActive class name. After than I press desc3 button. and desc2's desActive class removed and desc3 take desActive.

          <div  >
          <button >Description</button>
          <button >Reveiwes</button>
          </div>

CodePudding user response:

To dynamically attach/detach classes you can use ngClass (more here) or Class-Binding (more here).

ngClass

For both solution you need a variable to store information which button is currently selected.

comp.component.ts

// A helper variable to store the currently selected button
selected: number;

selectButton(selectNum: number){
  this.selected = selectNum;
}

comp.component.html

<div  >
  <button 
    (click)="selectButton(2)" 
    [ngClass]="{ 'desActive': selected === 2}" 
    
  >
    Description
  </button>

  <button 
    (click)="selectButton(3)" 
    [ngClass]="{ 'desActive': selected === 3}" 
    
  >
    Reviews
  </button>

</div>

Class-Binding

The Typescript part here would be the same as in the example above, so I don't add it here again.

But the HTML looks a bit different

comp.component.html

<div  >
  <button 
    (click)="selectButton(2)" 
    [class.desActive]="selected === 2" 
    
  >
    Description
  </button>

  <button 
    (click)="selectButton(3)" 
    [class.desActive]="selected === 3" 
    
  >
    Reviews
  </button>

</div>

NOTE: The Typescript part is just an example how you could store the selected button in a variable.

Update:

To solve the issue you mentioned in the comment you have two options.

Option 1:

Add a ? to the variable declaration

selected?: number;

The ? marks the variable as optional.

Option 2:

Initialize the variable in the constructor, e.g., with 2.

constructor(){
  this.selected = 2; 
}

I would recommend option 1 if you don't want to have a pre-selected button.

CodePudding user response:

<button [ngClass]="isActive ? 'desc2 desActive' : 'desc2'">Description

You can use above code if you are okay.

  • Related