代码之家  ›  专栏  ›  技术社区  ›  Deadpool

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

  •  1
  • Deadpool  · 技术社区  · 7 年前

    角度4, 在视图上(.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";
    

    我知道 ngStyles公司 ngClass公司 ,我只想问为什么属性绑定在上述情况下不起作用。如果值取自.ts文件并添加到段落中“style”属性前面的html代码段中,那么它就是一个简单的“内联CSS样式”。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Vikas RyanSand20    7 年前

    因为安全措施:

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

    • 将值解释为HTML时使用HTML,例如

    • 将CSS绑定到Style属性时使用Style。
    • URL用于URL属性,例如 <a href>.

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

    解决方法是使用 bypassSecurityTrustStyle() -绕过安全性并将给定的值信任为安全样式值(CSS)。

    @Angular docs

    警告:使用不受信任的用户数据调用此方法会暴露

    组成部分:

    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");
    }
    

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

    注:

    对于样式属性名称,请使用破折号大小写。 例如,字体大小、背景颜色

    Live Demo

        2
  •  1
  •   Nerijus Pamedytis    7 年前

    [style.background]="'red'"

    推荐文章