DEV Community

Pankaj Kumar
Pankaj Kumar

Posted on • Updated on

Angular 9/8 NgClass Directive example

It's very important to have a better understanding of using NgClass because there may be so much situation where we need to change the template as per the values inside the component ts file.

In this article, We will try to understand how class can be added dynamically into template as per the value inside ts file in Angular application. It is built in directive provided by angular.

The ngClass directive will take an expression that will be used to determine which state styles to apply at a given time to the styled element.

The expression passed on to ngClass can be:

an object
an array
a string

Let's Get Started

Using Simple Expression

There are two different ways by which NgClass can be used to add the class. The first way is by passing an object literal to the directive, like below:


[ngClass]="{'text-success':true}"

Enter fullscreen mode Exit fullscreen mode

In the above code, if the value is true then text-class will be added to the html element.

Second way is write the complete expression, like below:


[ngClass]="{'text-success':person.country === 'USA'}"

Enter fullscreen mode Exit fullscreen mode

Let's try to understand with below detailed example:

<h4>NgClass detailed example</h4>
<ul *ngFor="let user of users">
<li [ngClass]="{
'text-success':user.country === 'SA',
'text-primary':user.country === 'USA',
'text-danger':user.country === 'IN'
}">{{ user.name }} ({{ user.country }})
</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

Set Multiple Class on the same Element

There may be some cases when multiple classes need to add dynamically to the same HTML element on the base of different conditions. These cases can also be handled very easily with NgClass directive.


[ngClass]="{'actived':var1 !=null, 'active':var2 =='grade' }"

Enter fullscreen mode Exit fullscreen mode

In the above code, we can see on the base of two different conditions, two different classes are being added dynamically.

Using Ternary Operator

If there is a case where we have to set alternate class on the base of a variable value then ternary operator is used. See the code below:


<div [ngClass]="varA === varB ? 'css-class-1' : 'css-class-2'">

Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, We tried to understand the different ways to add classes dynamically in the Angular template. Check other Angular sample projects to start working on enterprise-level application

Thank

This article is originally posted over jsonworld

Top comments (0)