如何正确使用bypassSecurityTrustStyle

cur*_*hod 5 angular

我试图以Angular方式使用一些简单的CSS和JavaScript示例.

改变元素背景颜色的简单JavaScript方法如下所示:

this.container.style.backgroundColor = color;
Run Code Online (Sandbox Code Playgroud)

颜色是在JavaScript中随机创建的.模板看起来像这样:

<div id="container"
  (click)="changeColor($event)"
  [style]="{'color': color}">
</div>
Run Code Online (Sandbox Code Playgroud)

但是,这会产生以下错误:

WARNING: sanitizing unsafe style value [object Object] (see http://g.co/ng/security#xss).
Run Code Online (Sandbox Code Playgroud)

使用此功能不起作用:

this.color = this.sanitizer.bypassSecurityTrustStyle(this.color);
Run Code Online (Sandbox Code Playgroud)

创建一个函数也无法使用此样式[style.color] ="transform(color)"

transform(value) {
   return this.sanitizer.bypassSecurityTrustStyle(value);
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个plunker来演示这个问题.

使用纯JavaScript的正确行为显示在此页面的第一个示例中

这样做的正确方法是什么?任何帮助将非常感激.

cur*_*hod -4

示例 plunker 正确使用了bypassSecurityTrustStyle:

 this.color = this.sanitizer.bypassSecurityTrustStyle(this.color);
Run Code Online (Sandbox Code Playgroud)

但是,模板需要像这样设置值:

[style.background]="color"
Run Code Online (Sandbox Code Playgroud)

  • 我看不到 plunkr 中使用了“bypassSecurityTrustStyle”? (9认同)
  • 投反对票,因为 Plunker 是一个谎言。 (7认同)