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,
Example:-


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

Array – the CSS classes declared as Array elements are added,
Example:-


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

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


[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';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  implements OnInit{
  colorType:string='green';
  constructor(){
  }

  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 removeload.com</h1>
</div>

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.


.greenColor{color:green;}

Step4) Now run the URL on the browser.


http://localhost:4200/

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.


colorType:string='red';