To add a CSS class dynamically in Angular, you can use the ngClass
directive. The ngClass
directive allows you to add a single or multiple class to an element based on some condition.
The following syntax is used to add a class to an element using the ngClass
Directive:
<div [ngClass]="{'myClass' : condition}"></div>
Here, the class myClass
is added to the div element only when the condition evaluates to true. This condition can either be set in your ts file or in the template file as well.
If the condition evaluates to false, the class myClass will be removed from the div element.
Example:
Let’s say we have a div element which has some random text and we want to highlight it only when the marks of the student are more than 90.
Template file:
<div [ngClass]="{'highlight' : marks>90}">Some random text</div>
Set the value of marks in your ts file(When implementing it in a real scenario, the variable marks
will hold a dynamic value):
// Define variable marks in ts file marks: number = 95;
And finally, you have to define the class myClass inside your CSS file:
.highlight{ background: yellow; }
Add Multiple Classes using ngClass:
To add multiple classes using the ngClass
directive, you can simply separate them with a comma.
This is how you can do it:
<div [ngClass]="{ 'myClass1' : condition1, 'myClass2' : condition2, .. }"></div>
The div will have myClass1 when condition1 evaluates to true and myClass2 when condition2 evaluates to true.
Add Class Dynamically using [class.className] Binding
An alternative solution could be to bind the class name directly to the element. This is done using the [class.className] syntax.
<div [class.myClass]="condition"></div>
Here the div element will have the class myClass
only when the condition evaluates to true. This condition can either be defined inside the ts file or in the template file directly.
Example:
Let’s repeat the same marks example here also but with the class binding.
Here the only thing that will change is the class binding inside your template file. Rest other things will remain the same.
<div [class.highlight]="marks>90">This is some random text.</div>
The class highlight will be added to the div element only when the value of marks is greater than 90. Otherwise, it will be removed from the div if already exists.