Angular 8|9 NgClass Directive Tutorial With Example

By Digamber Rawat Last updated on
In this Angular 8|9 NgClass tutorial, we will learn to apply CSS classes to the HTML element using NgClass directive. If you are just getting started with Angular, then we would suggest you check out our Angular tutorials. NgClass is built-in directive provided by Angular, and it helps in adding or removing CSS classes on an HTML element. The NgClass directive allows you to apply CSS classes dynamically based on expression evaluation.

Understand Angular 8|9 NgClass Expressions

The NgClass directive is used via [ngClass] selector, and NgClass offers 3 simple ways through which we can update CSS classes in the DOM.

Expression Description
string The string method allows to apply class in string format.
Array The array method allows you to apply CSS classes in array form.
Object The object method allows to add classes in the key form, class gets added to the HTML element if it returns to true. If expression returns false then class is removed.

Setup Angular Web App

In order to show quick demo of NgClass directive, Install Angular web app. I believe you’ve already set up Node.js and Angular CLI in your machine. If not then consider this tutorial: Set up Node JS

Run command to install latest Angular CLI:

npm install @angular/cli -g

Once you are done setting up Node and Angular CLI, then run command to set up Angular web app:

ng new angular-ngclass-tutorial

# ? Would you like to add Angular routing? No
# ? Which stylesheet format would you like to use? CSS

Get into the app folder:

cd angular-ngclass-tutorial

Install Bootstrap 4 in Angular project, Bootstrap 4 offers robust UI components.

Integrate Bootstrap 4 CSS in angular.json to make the Bootstrap 4 UI components works:

npm install bootstrap
"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
         ]

Create An Interface Class and Array

In this step, we are going to create an Interface class to define the properties types of the cars array.

Run the command to create Interface class:

ng generate class Cars

Our cars collection has two properties name and color, go to src > app > cars.ts and add the following code:

export interface Cars {
    name: string;
    color: string;
}

Then, we will create the cars array in app.component.ts file same as given below:

import { Component } from '@angular/core';
import { Cars } from './cars';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  cars: Cars[] = [
    {
      "name": "MG Hector",
      "color": 'blue'
    },
    {
      "name": "Ford",
      "color": 'olive'
    },
    {
      "name": "Kia",
      "color": 'orange'
    },
    {
      "name": "BMW",
      "color": 'red'
    },
    {
      "name": "Jaguar",
      "color": 'green'
    },
    {
      "name": "Suzuki",
      "color": 'purple'
    }
  ];
}

Adding NgClass Directive on HTML Template in Angular 8|9

In this final step, we will learn to add the CSS classes dynamically to the HTML elements using Angular NgClass directive. In below example, we will learn to add NgClass object expression.

Go to app.component.html template and add the NgClass directive as mentioned below.

<div class="container">
  <div *ngFor="let car of cars" [ngClass]="{
    'alert-primary':car.name === 'MG Hector',
    'alert-secondary':car.name === 'Ford',
    'alert-success':car.name === 'Kia',
    'alert-danger':car.name === 'BMW',
    'alert-warning':car.name === 'Jaguar',
    'alert-info':car.name === 'Suzuki'
  }">
    {{ car.name }}
  </div>
</div>

In the above example, we are mapping cars name to apply the dynamic color classes, we declared NgClass object expression to apply the class. If the condition is true, it includes the class name on the HTML element if not, then it will discard the class name.

To view the working demo in your browser, run the following command:

ng serve --open

Following will be the output:

Angular 8|9 NgClass Directive

Conclusion

In this Angular 8|9 tutorial, we tried to understand how does NgClass work in an Angular app. We create the basic Angular app and learnt to apply the dynamic classes on HTML element using NgClass object expression. You can also check out how to use NgStyle in Angular 8|9 app. Thanks for reading, if you liked this tutorial then please consider it sharing with others.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.