Angular Style/ngStyle元素
 
 
  ngng属性用于更改或设置Angular的多个属性。您可以更改元素的值,颜色和大小等。
 
 让我们来看一个示例: 
 
  component.ts文件: 
 
 
  
  
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;
  }
} 
   
  
  component.html文件: 
 
 
  
  
<p>Server with ID {{serverID}} is {{serverStatus}}. </p> 
   
  
 在这里,我们选择一种方法来随机显示该方法"在线"和"离线"。有50%的机会。
 
  输出: 
 
 
 让我们在服务器离线时使用ngStyle更改背景颜色"红色",在服务器在线时使用"绿色"。 
 
  component.html文件: 
 
 
  
  
<p [ngStyle]="{backgroundColor: getColor()}">  Server  with ID {{serverID}} is {{serverStatus}}. </p> 
   
  
 在这里,我们创建了一个getColor()方法来动态更改颜色。
 
  输出: 
 
 
 如果两个服务器都在线,则它将为: 
 
 
 这是具有属性绑定功能的ngStyle属性示例。
 
如何应用使用ngClass 
动态创建CSS类
 在上一篇文章中,我们已经看到了如何使用ngStyle动态更改元素。在这里,我们将使用ngClass指令将CSS类应用于该元素。 
 
示例: 
 
 让我们在component.ts文件中创建一个类,它将更改文本黄色的颜色。如果服务器处于联机状态。
 
  component.ts文件: 
 
 
  
  
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';
  }
} 
   
  
  component.html文件: 
 
 
  
  
<p [ngStyle]="{backgroundColor: getColor()}"
[ngClass]="{Online: serverStatus === 'Online'}">  Server  with ID {{serverID}} is {{serverStatus}}. </p> 
   
  
  输出: 
 
 
 您可以看到ngClass指令已更改在线文本的颜色。这是带有属性绑定的ngClass指令示例,该绑定动态地应用CSS类。