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
ngClasswith multiple options:
- using multiple conditions:
- using method expression:
- using ternary operator:
3. More about
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
classes while rendering the view.
This will be rendered as:
[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,
ObjectMap - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.
In this article we showcased several ways to add
class to element conditionally in Angular.