个性化阅读
专注于IT技术分析

angular 7的ngstyle指令

本文概述

ngStyle属性用于更改或设置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>

在这里,%20we%20have%20choose%20a%20method%20to%20show%20the%20method%20randomly%20%22Online%22%20and%20%22Offline%22.%20There%20is%2050 %% 20chance。

输出:

让我们使用ngStyle在服务器离线时更改背景颜色“红色”,在服务器在线时更改“绿色”。

component.html文件:

<p [ngStyle]="{backgroundColor: getColor()}">  Server  with ID {{serverID}} is {{serverStatus}}. </p>

在这里,我们创建了一个getColor()方法来动态更改颜色。

输出:

如果两个服务器都在线,则它将为:

这是带有属性绑定以配置它的ngStyle属性的示例。

如何使用ngClass动态应用CSS类

在上一篇文章中,我们已经看到了如何使用ngStyle动态更改元素。在这里,我们将使用ngClass指令将CSS类应用于该元素。它有助于你动态添加或删除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类。


赞(0)
未经允许不得转载:srcmini » angular 7的ngstyle指令

评论 抢沙发

评论前必须登录!