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 </p> <button (click)="onButtonClicked()">Change Color</button>
import {Component, OnInit} from '@angular/core'; @Component({ 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; } }
.redBackground{ background: indianred; } .greenBackground{ background:greenyellow; }