Class Binding in Angular

The Angular Class binding is used to add or remove classes to and from the HTML elements. You can add CSS Classes conditionally to an element, hence creating a dynamically styled element.

The Angular provides the three ways to add/remove classes to and from the element. One using the DOM ClassName Property. The second option is to use the Class shorthand. The third option is to use the NgClass directive, which is covered in a separate tutorial.

Class binding with ClassName

The ClassName is the property name of HTML Element. Hence we can make use of Property binding to assign the class name to any HTML element.

The following example assigns CSS Class red to the div element.

You can also add more than one class by separating them using the

HTML Class attribute

You can also add class using the normal HTML way.

but, mixing both class and [className] results in removal of class attribute. You cannot use both.

Conditionally apply Classes

We can also bind the class name dynamically.

To do that first create a variable in your component class.

And then use it in the Template as shown below.

You can create a function, which returns the class based on some condition.

and then use it in the template as shown below.

The following example uses the Conditional (Ternary) Operator.

Class binding with Class

There are another shorthand way to bind CSS Class to HTML element.

Where

className is name of the class, which you want to bind to.

condition must return true or false. A return value of true adds the class and a false removes the class.

In the following example, the class red and size20 is added to the div element.

Conditionally binding class

To dynamically or conditionally bind a class, First create a variable in the component class as shown below.

You can also create a function hasError(), which should return true or false as shown below.

And use it in the template as shown below.

Class binding with NgClass

Another way to add class is to use the NgClass directive. It is offers a more flexibility, like easily adding multiple classes etc. You can read about ngClass in Angular.

Summary

The class binding is one of the many ways in which you can style angular apps. The following is the list of all articles on styling angular application.

Further Reading on Angular Styles

3 thoughts on “Class Binding in Angular”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top