2016-06-29 4 views
4

角度2 RC3角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を使用しています。しかし、私は同じ問題をプランナーで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では、DomSanitizationServiceの代わりにDomSanitizerを使用する必要があることに注意してください。 https://angular.io/docs/ts/latest/api/platform-b​​rowser/index/DomSanitizer-class.html –

関連する問題