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:
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}"
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'}"
Let's try to understand with below detailed example:
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' }"
In the above code, we can see on the base of two different conditions, two different classes are being added dynamically.
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'">
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
Thanks!