Angular ngClass Directive

What is Angular ngClass Directive?

ngClass Directive is basically used to add or remove class dynamically into the angular html template file.
It supports three types of expression to represent the classes.

Types of ngClass Directive?

There are three types of ngClass.

string – the CSS classes listed in the string (space delimited) are added,

[ngClass]="'redColor bg-color-white'"

Array – the CSS classes declared as Array elements are added,

[ngClass]="['redColor', 'bg-color-white']"

Object – the CSS classes declared into the Object elements based on the condition.

[ngClass]="{'redColor': colorType === 'red'}"

How to use Angular ngClass Directive?

Step1) Suppose, we create a file app.component.ts file and defined the below code.
In this file, we initialized the variable colorType and defined the value is green into it.

import { Component, OnInit} from '@angular/core';
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
export class AppComponent  implements OnInit{

  ngOnInit() : void{


Step2) Now we created a app.component.html file and defined the below code into it.

<div align="center" class="">
    <h1  [ngClass]="{'greenColor':colorType === 'green'}">Welcome to</h1>

In this file, we created the ngClass and defined the condition if colorType is green then class greenColor will be added.

Step3) Now create the class greenColor into the app.component.scss file.


Step4) Now run the URL on the browser.


Now, you can see greenColor class is added into the h1 tag.

Suppose, if we changed the colorType variable value from green to red then condition is failed and greenColor class will not add into the h1 tag.