1. Introduction
In this short tutorial we are going to present several ways to add a class
for HTML element conditionally in Angular.
2. Ways to add class
conditionally in Angular
- using
class.other_class
statement:
- using
ngClass
:
- using
ngClass
with multiple options:
- using multiple conditions:
- using method expression:
- using ternary operator:
3. More about ngClass
directive
In Angular ngClass
directive is used to add or remove classes
on HTML elements. This means if some element has a class
attribute, the [ngClass]
directive will add another class
or classes
while rendering the view.
This will be rendered as:
The [ngClass]
directive supports the following value types:
string
- CSS class or classes separated with space are added to HTML element,Array
- all CSS classes declared as Array elements are added using space separator,Object
Map - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.
4. Conclusion
In this article we showcased several ways to add class
to element conditionally in Angular.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}