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 the parenthesis the ouput looks like this in the DOM.
<div style="unsafe"></div>
If I take out the parenthesis it works (sort of) It looks like this.
<div style="calc10% - 20px"></div>
This also doesn't work.
<div attr.style.width="calc({{width}} - 20px)">
Any help on how to add calc() to the template is much appreciated. Note I also tried replacing the parenthesis with ( and ). That also came back as "unsafe".
Example: (rc1)
I am using rc3 in my environment. But I was able to reproduce the same issue with RC1 in plunker. I am assuming this is a security thing. But there must be a way to add calc() to a style attribute. Maybe there is a better way than this?
https://plnkr.co/edit/hmx5dL72teOyBWCOL0Jm?p=preview
You can also try using ngStyle instead:
[ngStyle]="{'width': 'calc(' + percent + '% - 20px)'}"
And just bind 'percent' value to the input value.
Calculated styles should be sanitized.
Here is the solution for you:
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)");
  }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With