Angular dynamically add and remove CSS Classes using ngClass | custom directive

In this tutorial, we will learn and demonstrate a dynamically Angular add and remove class on the host element based on specific conditions using a custom directive and ngClass directive.

To create and run an Angular project, We need Node js and Angular CLI already install in our system, if not then check how to install Node js and angular in Ubuntu. To install the latest version of Angular CLI, open a terminal and run the following command:

Angular add and remove class using ngClass

We can also use the NgClass directive to dynamically add and remove classes based on certain conditions on NgClass. Angular has a lot of built-in directives, we have structure directives like *ngIf, *ngFor, *ngSwitch .

These directives manipulate the DOM element by adding or removing elements based on condition. The ngClass directive is a built-in directive. The ngClass in Angular allows us to change the appearance of DOM elements by adding or removing classes using ngClass directive on based condition expression.

Syntax of ngClass directive allows Angular add and remove class.

<any-element [ngClass]="{selected: isSelected}">


<any-element [ngClass]="{selected: isSelected, disabled: isDisabled}">

An example of ngClass to add a class based on condition and we are setting font color white and background: red for even number using ngClass.

<p *ngFor="let number of numbers"  [ngClass]="{'even': number % 2 === 0}">
  {{ number }}

In the previous few articles where we have learned details on angular directives and how to create an angular custom directive. We’ll create two examples, first to add and remove the warning class on the card header, and the second example to Angular add and remove a class to hide the div element.

npm install -g @angular/cli

We’ll demonstrate here’s a quick screenshot of what we’ll be building.

Angular custom directive to add and remove CSS class

Setup and configure Angular add and remove class project

Create an angular project and add two custom directives. The first directive is to add/remove the warning background color of the card header by clicking on the card header. The second directive is to show/hide div by clicking a button to add/remove CSS class.

ng new customDirectiveApp
ng generate directive cssToogle
ng generate directive collapse

Edit app.component.ts file to add two custom directive.

We have two custom directive attributes in app.component.html. The first is appCssToggle on card-header to control background-color by adding and removing bg-warning on host element in the css-toggle.directive.ts.
The second directive collapseEl attribute on a button to toggle to show/hide sibling element by collapse.directive.ts

import { Component } from '@angular/core';

  selector: 'app-root',
  template: `
  <div class="container">
  <h2>Card Header and Footer</h2>
  <div class="card">
    <div class="card-header" appCssToggle>Header</div>
    <div class="card-body">Content</div>
    <div class="card-footer">Footer</div>

  <div class="mt-2">
    <button class="btn btn-primary" appCollapse type="button" data-toggle="collapse" data-target="#collapseExample">
      Button with data-target

    <div class="collapse" id="collapseExample">
      <div class="card card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim
        keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
  styleUrls: ['./app.component.scss']
export class AppComponent { }

Create a custom CSS toggle.directive.ts directive.

The @HostListener decorator allows a directive to listen to events on its host element, in our case, it is the card header div element. When a user clicks on the card header we will add/remove CSS class bg-warning using @HostBinding(). We have used the angular hostbinding class toggle class on add and remove.

import { Directive, HostBinding, ElementRef, HostListener } from '@angular/core';

  selector: '[appCssToggle]'
export class CssToggleDirective {
  @HostBinding('') isBgWarning = false;

  constructor(private elRef: ElementRef) { }

  @HostListener('click', ['$event']) toggleOpen(event: Event) {
    this.isBgWarning = !this.isBgWarning;

Create a custom CSS collapse.directive.ts directive

The @HostListener decorator will listen to the click event on the host element, in our case, it is a button. When a user clicks on the button we will use renderer2 to retrieve the next sibling element. We will use renderer2 to add/remove the show class on a sibling element to control the hide/show sibling element.

import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

  selector: '[appCollapse]'
export class CollapseDirective {
  isShow = true;

  constructor(private elRef: ElementRef, private renderer: Renderer2) { }
  @HostListener('click', ['$event']) toggleOpen() {
    const nextEl = this.renderer.nextSibling(this.elRef.nativeElement);
    this.isShow = !this.isShow;
    if (this.isShow) {
      this.renderer.addClass(nextEl, 'show');
    } else {
      this.renderer.removeClass(nextEl, 'show');

We have explored Angular custom directives to add and remove a class to control div element style and content. Angular Attribute directive changes the appearance or behavior of a DOM element.

Related Articles

Spread the love

Leave a Comment

Your email address will not be published.

Scroll to Top