Angular 6, ngStyle 指令中 css 文件的颜色

Angular 6, color from css file in ngStyle directive

我想为我的 ngStyle 指令(在 HTML 中)使用 CSS 文件中定义的颜色。

这是我 HTML 中的内容:

 [ngStyle]="{backgroundColor: isDarkStyle() ? '#29434e' : isNormalStyle() ? '#cfd8dc' : isLightStyle() ? 'white': ''}"

这是我的 CSS 颜色文件:

//colors for background

$light-background: white;
$normal-background: #cfd8dc;
$dark-background: #29434e;

但我想要这个:

[ngStyle]="{backgroundColor: isDarkStyle() ? '$dark-background' : isNormalStyle() ? '$normal-background' : isLightStyle() ? '$light-background': ''}"

我怎样才能达到这个结果?感谢您的帮助:)

使用[ngClass]

查看 stackblitz:https://stackblitz.com/edit/hello-angular-6-refjye?file=src%2Fapp%2Fapp.component.html

.light{
background: white;
}
.normal{
background: #cfd8dc;
}
.dark{
background: #29434e;
}

在Html

<p [ngClass]="isDarkStyle() ? 'dark' : isLightStyle() ? 'light': isNormalStyle()?'normal':''">
  Start editing to see some magic happen :)
</p>

try solution

据我了解你的问题:

HTML:

<h1 [ngStyle]="{backgroundColor: isDarkStyle() ? 'red' : isNormalStyle() ? 'green' : isLightStyle() ? 'white': ''}">Text</h1>

TS:

isDarkStyle() {
    return false
  }

  isNormalStyle() {
    return true
  }

  isLightStyle() {
    return true;
  }

您可以定义ngClassngStyle

ngClass 需要在样式文件中定义 class

<h1>ngClass</h1>
<p [attr.class]="state">
  Start editing to see some magic happen :)
</p>
<button (click)="state = 'light'">light</button>
<button (click)="state = 'dark'">dark</button>
<button (click)="state = 'normal'">normal</button>

ngStyle 您可以更改 spisifc css 属性,例如 background-color

<h1>ngStyle</h1>
<p [ngStyle]="{'background-color':color}">
    Start editing to see some magic happen :)
</p>
<button (click)="color = '#fff'">light</button>
<button (click)="color = '#cfd8dc'">dark</button>
<button (click)="color = '#29434e'">normal</button>

stackblitz example