Angular 16 NgClass Directive Tutorial With Example

Last Updated on by in Angular
Angular NgClass tutorial; NgClass is the most popular directive in angular, and it allows you to add and remove CSS classes on an HTML element in Angular.In this tutorial, we will show you how to use the NgClass directive in Angular to manage CSS classes.

Here in this guide, we will demonstrate the simple methods that will help you learn to apply CSS classes to the HTML element using NgClass directive.

The NgClass directive allows you to apply CSS classes dynamically based on expression evaluation.

Understand Angular 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 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

Get into the app folder:

cd angular-ngclass-tutorial

In order to remove strict type warnings or error make sure to set “strict”: false under compilerOptions property in tsconfig.json file.

Install Bootstrap 5 in Angular project, it offers robust UI components.

Integrate Bootstrap CSS in angular.json to make the Bootstrap 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

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">
  <li class="alert" *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 }}
  </li>
</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 NgClass Directive

Conclusion

The NgClass directive is a built-in directive in Angular, a popular JavaScript framework for building web applications.

The NgClass directive allows you to dynamically add or remove CSS classes to an HTML element based on certain conditions or expressions.

In this 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.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.