角度6,来自ngStyle指令中的CSS文件的颜色

时间:2018-07-17 08:05:04

标签: html css angular ng-style

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

这就是我的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': ''}"

如何获得此结果?感谢您的帮助:)

3 个答案:

答案 0 :(得分:1)

使用gbifmap

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

[ngClass]

以HTML格式

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

答案 1 :(得分:0)

try solution

据我了解,您的任务:

HTML:

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

TS:

isDarkStyle() {
    return false
  }

  isNormalStyle() {
    return true
  }

  isLightStyle() {
    return true;
  }

答案 2 :(得分:0)

您可以定义ngClassngStyle

ngClass 要求在样式文件中定义类

<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