Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2, Adding calc() as inline style. Unsafe interpolation using parentheses

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 &#40; and &#41;. 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

like image 260
Kris Hollenbeck Avatar asked Jun 29 '16 21:06

Kris Hollenbeck


2 Answers

You can also try using ngStyle instead:

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

And just bind 'percent' value to the input value.

like image 78
indreed Avatar answered Nov 15 '22 09:11

indreed


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)");
  }
}
like image 22
Andrei Zhytkevich Avatar answered Nov 15 '22 10:11

Andrei Zhytkevich