Learnitweb

Binding to the class attribute in Angular

In this article, we’ll read how to bind to the class attribute in Angular. We can dynamically add and remove classes to an element using class binding. his is a very helpful feature from user interface point of view. There are many scenarios when we want to apply color coding based on some expression. For example, show active status in green and inactive status in red color. This is just an example and we can do much more by applying and removing classes to an element.

Binding to a single CSS class

The syntax to bind to a single CSS class is:

[class.classToBind]="expression"

Here, classToBind class will be added to the element when expression is truthy and classToBind class will be removed from the element if the expression is falsy.

Example

Following is a very simple example to show active status in green and inactive status in red.

app.component.html

<p [class.active]="undefined">Active</p>
<p [class.inactive]="status === 'inactive'">Inactive</p>

app.component.ts

//toggle between active and inactive values to test

status = 'active';
//status = 'inactive'

app.component.css

.active {
  color: green;
}

.inactive {
  color: red;
}

Binding to multiple CSS classes

The syntax to bind multiple classes is:

[class] = "expression"

The expression can be one of the following:

1. A space-delimited string of class names

[class]="myclass-1 myclass-2 myclass-3"

2. An object with keys as class names and truthy or falsy expressions as the values

[class]="{myclass-1: true, myclass-2: false}”

The class is added when the value is truthy.

3. An array of class names

[class]=['myclass-1', 'myclass-2']

Conclusion

In this article we discussed binding to the class attribute in Angular. We should know about the syntax very well as it is very commonly used. We hope this article was informative for you. Happy learning!