【问题标题】:Angular 2, Adding calc() as inline style. Unsafe interpolation using parenthesesAngular 2,添加 calc() 作为内联样式。使用括号的不安全插值
【发布时间】:2016-06-29 21:06:05
【问题描述】:

Angular 2 rc3

我正在尝试将calc() 动态添加到模板中的元素。我有这样的东西。

template : `<div attr.style.width="{{width}}></div>"`

export myClass
{
    @Input() myInputObject:any;
    private width:string;


   ngOnInit() { this.setWidth()}

   private setWidth()
   {
       let percent = myInputObject.percent;
       this.width =  'calc(' + percent + '% - 20px)';
   }
}

如果我使用括号,则输出在 DOM 中如下所示。

&lt;div style="unsafe"&gt;&lt;/div&gt;

如果我去掉括号,它会起作用(有点)它看起来像这样。

&lt;div style="calc10% - 20px"&gt;&lt;/div&gt;

这也行不通。

<div attr.style.width="calc({{width}} - 20px)">

非常感谢任何有关如何将calc() 添加到模板的帮助。注意我还尝试用&amp;#40; 和&amp;#41; 替换括号。这也被认为是“不安全的”。

示例:(rc1)

我在我的环境中使用 rc3。但是我能够在 plunker 中用 RC1 重现相同的问题。我假设这是一个安全的事情。但是必须有一种方法可以将calc() 添加到样式属性中。也许还有比这更好的方法?

https://plnkr.co/edit/hmx5dL72teOyBWCOL0Jm?p=preview

【问题讨论】:

    标签: javascript angular interpolation


    【解决方案1】:

    计算后的样式应净化。

    以下是适合您的解决方案:

    import {DomSanitizationService} from '@angular/platform-browser';
    
    @Component({
      selector: 'my-app'
      template: `
        <div [style.width]="width">
          <h2>Hello {{name}}</h2>
        </div>
      `
    })
    export class App {
    
      private width:string;
    
      constructor(sanitizer: DomSanitizationService) {
        this.name = 'World'
        this.width = sanitizer.bypassSecurityTrustStyle("calc(10% - 20px)");
      }
    }
    

    【讨论】:

    • 感谢您的回复。我会在今天某个时候尝试一下,然后回复您。
    • 请注意,在 RC6 中我需要使用 DomSanitizer 而不是 DomSanitizationService。 angular.io/docs/ts/latest/api/platform-browser/index/…
    • 它在 Mozilla Firefox 中不起作用。在 Chrome 和 IE 中它可以工作,有什么帮助吗?
    【解决方案2】:

    您也可以尝试使用 ngStyle:

    [ngStyle]="{'width': 'calc(' + percent + '% - 20px)'}"
    

    只需将“百分比”值绑定到输入值。

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 2017-11-25
      • 2019-04-11
      • 1970-01-01
      相关资源
      最近更新 更多