简体   繁体   English

Angular 6将Html中的背景颜色设置为CSS变量

[英]Angular 6 set Background Color in Html to CSS Variable

I am using Angular 6 and I have a simple div and want to set the background color of this div from inside the template. 我正在使用Angular 6,我有一个简单的div并希望从模板内部设置此div的背景颜色。 This works fine when passing normal colors. 传递正常颜色时效果很好。 But this does not work with CSS Variables. 但这不适用于CSS变量。

This example works 这个例子有效

<div [style.background]="'red'">...</div>

This example does not work 此示例不起作用

<div [style.background]="'var(--some-css-var)'">...</div>

You have to use ngStyle 你必须使用ngStyle

<some-element [ngStyle]="{'background-color': styleExp}">...</some-element>

https://angular.io/api/common/NgStyle https://angular.io/api/common/NgStyle

In order to bind a style property to a CSS variable in the HTML template, the CSS variable expression var(...) must be sanitized. 为了将样式属性绑定到HTML模板中的CSS变量,必须清理CSS变量表达式var(...) You can define a custom pipe: 您可以定义自定义管道:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

@Pipe({
  name: 'safeStyle'
})
export class SafeStylePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }

  transform(value: string): SafeStyle {
    return this.sanitizer.bypassSecurityTrustStyle(value);
  }
}

and use it in the HTML template: 并在HTML模板中使用它:

<div [style.background-color]="'var(--some-css-var)' | safeStyle"></div>
<div [style.background-color]="bkColor | safeStyle"></div>
bkColor = "var(--some-css-var)";

See this stackblitz for a demo. 有关演示,请参阅此stackblitz

You can do it in 2 ways 你可以用两种方式做到这一点

  1. use pipe that get a string and return some color code code. 使用获取字符串的管道并返回一些颜色代码。

     <div [style.background-color]="someString | colorSetter"></div> 
  2. add to the html tag a dynamic class for example: 添加到html标记的动态类例如:

    <div class="my-div" [class]="someClassName"></div>

and in the scss add the options 并在scss中添加选项

scss: SCSS:

.my-div{
    &.optoin1{
       background-color:red;
     }
&.optoin2{
       background-color:black;
     }
&.optoin3{
       background-color:green;
     }
&.optoin4{
       background-color:yellow;
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM