How to Add a Class Conditionally in Angular?

javascript

To add a class conditionally in Angular, you can use the [ngClass] directive or the [class] binding.

Example using [ngClass]:

<div [ngClass]="{'my-class': condition}">
  ...
</div>

In this example, the class 'my-class' will be added to the div element when the condition is true.

Example using [class] binding:

<div [class.my-class]="condition">
  ...
</div>

In this example, the class 'my-class' will be added to the div element when the condition is true. Note that the syntax is slightly different from the previous example.

You can also add multiple classes using either method by providing an object with multiple key-value pairs, like this:

<div [ngClass]="{'my-class': condition, 'another-class': anotherCondition}">
  ...
</div>

<div [class.my-class]="condition" [class.another-class]="anotherCondition">
  ...
</div>

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?