NgClass Directive
The ngClass
directive changes the class
attribute that is bound to the component or element it's attached to. There are a few different ways of using the directive.
Binding a string
We can bind a string directly to the attribute. This works just like adding an html class
attribute.
In this case, we're binding a string directly so we avoid wrapping the directive in square brackets. Also notice that the ngClass
works with the class
attribute to combine the final classes.
Binding an array
Here, since we are binding to the ngClass
directive by using an expression, we need to wrap the directive name in square brackets. Passing in an array is useful when you want to have a function put together the list of applicable class names.
Binding an object
Lastly, an object can be bound to the directive. Angular applies each property name of that object to the component if that property's value is true.
Here we can see that since the object's card
and flat
properties are true, those classes are applied but since dark
is false, it's not applied.
Last updated