ngClass Directive

To demonstrate ngClass directive we first create an angular project using angular CLI.

Write the below contents in app.component.html file

<h1> ng Class Demo</h1>
<button (click)="onButtonClick()" >Click me to change Style Clas</button>
<p [ngClass]="{defaultCss : toggle==true}">Hello World, the color of this paragraph changes with button click</p>

Write the below contents in app.component.ts file

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styles: [`
      .defaultCss{
        color : white;
        background-color : maroon;
      }
  `]
})
export class AppComponent {
  title = 'ngClassDemo';
  toggle = false;
  onButtonClick(){
    if(this.toggle) {
      this.toggle = false;

    } else{
      this.toggle = true;
    }
  }
}

And the output looks like below : On button click the class is applied to the paragraph tag

Leave a Comment