2016-06-29 24 views
4

角2 RC3Angular 2,以内联样式添加calc()。不安全使用插值括号

我试图动态地添加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中看起来像这样。

<div style="unsafe"></div>

如果我拿出它的工作原理括号(那种)它看起来像这样。

<div style="calc10% - 20px"></div>

这也不起作用。

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

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

例子:(RC1)

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

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

回答

10

计算方式应消毒

这里是为您解决:

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

感谢您的答复。我会在今天的某个时候尝试一下并回复你。 –

+0

这可行。谢谢。 –

+3

请注意,在RC6中,我需要使用DomSanitizer而不是DomSanitizationService。 https://angular.io/docs/ts/latest/api/platform-b​​rowser/index/DomSanitizer-class.html –

相关问题