Directive ngClass

Assume we have a component called servers. ngClass directive can dynamically change the CSS class of an element. Different from ngStyle, we need a to use the component CSS file this time to set the style.

ngClass take an array of 'css_class_name' : boolean expression pair. If the expression is true, it will dynamically add the css_class_name in to the related HTML element.

<p [ngClass]="{
  'redBackground':  bIsBackgroundRed,
  'greenBackground':  !bIsBackgroundRed
  The button is clicked
<button (click)="onButtonClicked()">Change Color</button>
import {Component, OnInit} from '@angular/core';

  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
export class ServersComponent implements OnInit {
  bIsBackgroundRed: boolean;

  constructor() {

  ngOnInit() {
    this.bIsBackgroundRed = false;

  onButtonClicked() {
    this.bIsBackgroundRed = true;
  background: indianred;

  • ng/directive_ngclass.txt
  • Last modified: 2019/11/18 17:00
  • by chongtin