ngClass in angular

In this article, you will learn what is ngClass and how to use it with examples.

What is ngClass?

The ngClass is directive in angular. You can set single or multiple CSS classes to HTML elements using ngClass.

How to use ngClass?

You can use it by following methods:

For applying classes by using following methods for ngClass, put following CSS classes in CSS file.

.btn {
  padding: 10px;
  border-radius: 5px;
}

.btn-primary {
  background: blue;
  color: white;
  border: 1px solid blue;
}

.btn-warning {
  background: #c6c609;
  color: white;
  border: 1px solid #c6c609;
}

.btn-danger {
  background: #ca4141;
  color: white;
  border: 1px solid #ca4141;
}

**Note:

Put the above CSS classes in the component’s relative CSS file i.e if you are working in AppComponent then put the above classes in the app.component.css file.

1. By listing CSS classes in the string

You can set CSS classes to an element by listing CSS classes in the string. If you want to set multiple classes, those classes have to be separated by giving spaces between them.

Example:

<button [ngClass]="'btn btn-primary'">Submit</button>

Output:

2. By declaring CSS classes as array elements

You can set CSS classes to elements by declaring CSS classes in the array as elements of an array.

Example:

<button [ngClass]="['btn', 'btn-danger']">Delete</button>

Output:

3. By using object

You can set CSS classes by giving CSS classes as keys of an object and that classes get added when the expression given as value has truthy value. If the expression doesn’t have truthy value, then classes are removed.

Example:

<button [ngClass]="{'btn btn-warning': username === 'John'}">Cancel</button>

or you can set the above classes by using the below code also.

<button [ngClass]="{'btn': username === 'John', ' btn-warning': username === 'John'}">Cancel</button>

Output:

Conclusion:

From this article, you learned what is ngClass, when to use it and how to use it. If you have problems while implementing code, you can ask me through the comment section.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments