How to Add Multiple CSS Classes in Angular?

To add multiple CSS classes in Angular you can use the ngClass directive. The ngClass directive is used to add a single or multiple class to an element dynamically(condition based).

In order to add multiple classes using the ngClass directive, you have to separate each pair of the class and condition with a comma and you can add as many classes as you want.

This is how you can do it:

<div [ngClass]="{'class1': condition1, 'class2': condition2, ...}"></div>

The class1 will be added to the div element if condition1 evaluates to true, class2 will be added if condition2 evaluates to true and so on.


Example:

Let’s say we want to add two classes highlight and bold to a div element based on the marks of the student.

If the student’s marks are greater than 80, we want to highlight the text and if the marks are greater than 90, we also want to make the text bold.

This is what you need to add to your template file:

<div [ngClass]="{'highlight': marks>80, 'bold': marks>90}" >John Doe</div>

Secondly, you have to declare the variable marks inside your ts file. In real scenarios, the variable marks will hold a dynamic value.

// Declare variable marks
marks: number = 95;

Next, you need to define both classes inside your component’s CSS file:

.highlight{
    background: yellow;
}
.bold{
    font-weight: bold;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.