Angular 2, adding calc () as an inline style. Insecure Parenthesis Interpolation

Angular 2 rc3

I am trying to dynamically add calc() to an element in a template. I have something like this.

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

If I use a parenthesis, then the output in the DOM looks like this:

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

If I choose a bracket, it works (sort of). She looks like this.

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

This also does not work.

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

Any help on adding calc() to the template is much appreciated. Note. I also tried replacing the brackets with &#40; and &#41; . It also returned as "unsafe."

Example: (rc1)

I use rc3 in my environment. But I was able to reproduce the same problem with RC1 in plunker. I guess this is a safety thing. But there must be a way to add calc() to the style attribute. Maybe there is a better way than this?

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

+9
source share
2 answers

Designed styles should be sanitized .

Here is the solution:

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

You can also try using ngStyle:

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

And just bind the percent value to the input value.

+3
source

All Articles