Show pageBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== 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. {{ :ng:ngclass.png?nolink&400 |}} ===== servers.component.html===== 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. <code> <p [ngClass]="{ 'redBackground': bIsBackgroundRed, 'greenBackground': !bIsBackgroundRed }"> The button is clicked </p> <button (click)="onButtonClicked()">Change Color</button> </code> ===== servers.component.ts===== <code> 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; } } </code> ===== servers.component.css ===== <code> .redBackground{ background: indianred; } .greenBackground{ background:greenyellow; } </code> ng/directive_ngclass.txt Last modified: 2019/11/18 17:00by chongtin