在样式 属性 上使用时,Angular4 中的 属性 绑定有什么问题?

What is wrong with this property binding in Angular4 while using it on style property?

在 Angular4 中,属性 视图 (.html) 上的绑定 从逻辑文件 (.ts) 中获取值

这在代码中运行良好:

<img [src]="sourceValue"> 

这在代码中也很有效:

<button [disabled]="isDisabled"> 

为什么这不起作用?

<p [style]="paragraphStyle"> This is a paragraph.</p>

abc.component.ts

isDisabled:boolean = true; 
sourceValue:string = "./assets/hermione.jpg"; 
paragraphStyle:string = "background:red; color:yellow";

我知道ngStylesngClass的用法,我只是想问一下为什么属性绑定不起作用以上案例。最后 --- 只是一个简单的 "Inline CSS Styling" 如果从 .ts 文件中获取值并添加到段落中 'style' 属性 前面的 html 片段。

我认为你可以做到,但你必须这样做: [style.background]="'red'"

这是因为安全措施:

@Angular docs
Angular 定义了以下安全上下文:

  • HTML用于将一个值解释为HTML,例如,当
    绑定到 innerHtml.
  • 将 CSS 绑定到样式 属性 时使用样式。
  • URL 用于 URL 属性,例如 <a href>.

  • 资源URL是一个URL,将作为代码加载和执行, 例如,在 <script src>.

解决方法是使用 bypassSecurityTrustStyle() 预先清理值 - 绕过安全性并相信给定值是安全样式值 ​​(CSS)。

@Angular docs

WARNING: calling this method with untrusted user data exposes your application to XSS security risks!

分量:

import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  paragraphStyle;
constructor(private _sanitizer: DomSanitizer){ 

  this.paragraphStyle=this._sanitizer.bypassSecurityTrustStyle("background-color:red");
}

HTML

<p [style]="paragraphStyle"> This is a paragraph.</p>

注意:

For style property name use dash-case. For example, font-weight ,background-color

Live Demo