1

I have a div in angular and I want to toggle between 3 classes.

So in the html I have:

<div *ngIf="status">Content Here</div>

In my .ts file I have a variable:

status = 'closed';

The status can have 3 values...

closed, opened or hidden.

Depending on the status value I need to add a different class or css to the div.

How can I do that?

ojy2021
  • 57
  • 4
  • See [Angular: conditional class with *ngClass](https://stackoverflow.com/questions/35269179/angular-conditional-class-with-ngclass) – pzaenger Feb 10 '21 at 16:41

2 Answers2

3

You need to use ngClass to achive this.

 <div *ngIf="status" 
       [ngClass]="{'closedClass': status == 'closed', 
                   'openedClass': status == 'opened', 
                   'hiddenClass': status == 'hidden' }">Content Here</div>

Hope this helps :)

Msk Satheesh
  • 1,398
  • 1
  • 6
  • 7
1

There are many ways, the easiest is:

<div [class.class1]="status == 'closed'" [class.class2]="status == 'opened'" [class.class3]="status == 'hidden'">Content Here</div>

You can also use ngClass:

<div [ngClass]="{ 'class1':status == 'closed', 'class2':status == 'opened' ... }"></div>
Soukyone
  • 568
  • 2
  • 13