NgClass vs Class Binding in Angular

Like data, we can bind classes to elements in angular. To set some style conditionally on any element we can simply write the CSS styles on a class selector and we can add that CSS class conditionally to any element.

Class Binding

To add or remove a CSS class dynamically from an element we can make use of class binding. Syntax is:

[classs.className] = "boolean expression"

If the given Boolean expression is truthy then the provided class will be added or if it is falsey then it will be removed from the element. For Example:

<div [class.error]="hasError"> </div> 
<div [class.adult]="age >= 18 ? true : false"> </div>

With class binding, we can add only a single class conditionally. However, to set multiple classes we can use ngClass directive.

The ngClass Directive

To add multiple classes, we can pass an object where the key will be class names and values will be respective boolean expressions.

<div [ngClass]="{'error': hasError, 'warning': hasWarning}"> </div>

If the boolean expression is truthy, the respective class will be added to the element.

If we have a more complex object to pass to ngClass, we can also define the object in the component and we can use that object in the template.

classes = {
    'hasValue': this.password.length > 0,
    'valid': this.password.length >= 6,
    'invalid': this.password.length < 6,
}
<div [ngClass]="classes">
...
</div>

We can also pass a string and array values to ngClass.

<div [ngClass]="'box'"> </div>
<div [ngClass]="['box', 'card', 'container']">
...
</div>

Now you are all set to add dynamic classes to your HTML elements with whichever binding is appropriate for you.

Related

NgStyle vs style binding in Angular