Understanding NgClass

Understanding ngClass

Angular comes bundled with a built-in directive called ngClass which allows the developers to dynamically add or remove the CSS classes.

In this post, we will learn to utilize this directive to effectively attach or detach CSS classes.

The simplest way to use ngClass is to provide the class name as a string value.

<div [ngClass]="'heading'">Dashboard</div>

The above code will add heading class to the div element.

You can also attach multiple class to the element.

<div [ngClass]="'heading main'">Dashboard</div>

Angular also allows you to apply classes using an array-like syntax.

<div [ngClass]="['heading', 'main']">Dashboard</div>

The above code will add the heading and main classes to the div element.

You can also use variables instead of plain strings.

<div [ngClass]="upperText">Dashboard</div>
<div [ngClass]="[label, type]">Dashboard</div>

In the above code upperText, label and type are variables which hold the name of CSS classes.

You can also use an object literal when we need to apply classes based on certain conditions.

<div [ngClass]="{'active': isActive}">Dashboard</div>

In the above code, the active class will be added to the div element only if the isActive variable holds a truthy value.

You can also specify multiple conditions.

<div [ngClass]="{'active': isActive, 'inactive': !isActive}">Dashboard</div>

In the above code, if isActive is true active class will be added to the div element otherwise it will add the inactive element.

For more Information: https://angular.io/api/common/NgClass

One thought on “Understanding NgClass”

Leave a Reply

Your email address will not be published. Required fields are marked *