How to use conditional class with ngClass in angular

How to use conditional class with ngClass in angular

In this article let’s understand how to use conditional class with ngClass in angular.

In Angular, you can apply conditional classes to elements using the *ngClass directive. The *ngClass directive allows you to dynamically add or remove CSS classes based on specific conditions. Here’s an example of how you can use *ngClass to apply a conditional class:

<div [ngClass]="{'class-name': condition}">
  Content goes here...
</div>

In the above code snippet, the ngClass directive is applied to the <div> element.

The value of ngClass is an object with the class name as the key and the condition as the value. When the condition evaluates to true, the class will be applied; otherwise, it will be removed.

Here’s a breakdown of the code:

  • 'class-name': The CSS class you want to apply conditionally. For example : “showDiv”
  • condition: The expression that determines whether the class should be added or removed. This can be a variable, a function call, or any other expression that resolves to a boolean value.

You can also apply multiple conditional classes by extending the object inside ngClass. For example:

<div [ngClass]="{'class-one': condition1, 'class-two': condition2, 'class-three': condition3}">
  Content goes here...
</div>

In this case, class-one will be applied if condition1 is true, class-two will be applied if condition2 is true, and so on.

You can also use more complex expressions or functions to determine the conditions for applying classes. For example:

<div [ngClass]="{'class-name': myFunction() > 5}">
  Content goes here...
</div>

In this example, the class-name class will be applied if the result of the myFunction() call is greater than 5.

By using the *ngClass directive with conditional expressions, you can easily apply or remove classes based on dynamic conditions in your Angular templates.

This is all about how to use conditional class with ngClass in angular.