import {Component} from '@angular/core'; @Component( {selector: 'app-server', templateUrl: 'server.component.html'}) export class ServerComponent { serverID: number = 10; serverStatus: string = 'Offline'; constructor () { this.serverStatus = Math.random() > 0.5 ? 'Online' : 'Offline'; } getServerStatus() { return this.serverStatus; } }
<p>Server with ID {{serverID}} is {{serverStatus}}. </p>
<p [ngStyle]="{backgroundColor: getColor()}"> Server with ID {{serverID}} is {{serverStatus}}. </p>
动态创建CSS类
import {Component} from '@angular/core'; @Component( {selector: 'app-server', templateUrl: 'server.component.html', styles: [` .Online{ color: yellow; }`] }) export class ServerComponent { serverID: number = 10; serverStatus: string = 'Offline'; constructor () { this.serverStatus = Math.random() > 0.5 ? 'Online' : 'Offline'; } getServerStatus() { return this.serverStatus; } getColor() { return this.serverStatus === 'Online' ? 'green' : 'red'; } }
<p [ngStyle]="{backgroundColor: getColor()}" [ngClass]="{Online: serverStatus === 'Online'}"> Server with ID {{serverID}} is {{serverStatus}}. </p>