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.
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.
<div [className]="'red'">Test</div>
You can also add more than one class by separating them using the
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.
<div class="red" [className]="'size20'">red</div>
We can also bind the class name dynamically.
To do that first create a variable in your component class.
cssStringVar: string= 'red size20';
And then use it in the Template as shown below.
<div [className]="cssStringVar">Test</div>
You can create a function, which returns the class based on some condition.
getClass() {
return 'red';
}
and then use it in the template as shown below.
<div [className]="getClass()">getClass</div>
The following example uses the Conditional (Ternary) Operator.
<div [className]="hasError() ? 'red' : 'size20'"> conditonal operator </div>
There are another shorthand way to bind CSS Class to HTML element.
<div [class.<className>]="condition"></div>
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.
<div [class.red]="true" [class.size20]="true">Test</div>
To dynamically or conditionally bind a class, First create a variable in the component class as shown below.
hasError:false;
<div [class.red]="hasError" [class.size20]="hasError">Test</div>
TYou can also create a function hasError(), which should return true or false as shown below.
hasError() {
return false
}
And use it in the template as shown below.
<div [class.red]="hasError()" [class.size20]="hasError()">Test</div>
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.
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