Angular - How do I sanitize a style inside a plain typescript class?

5.5k Views Asked by At

I'm running into this problem.

WARNING: sanitizing unsafe style value rotate(36.362868584929245deg)translate(91px,67px) (see http://g.co/ng/security#xss).

Now, after some reseach, I found I have to use the DomSanitizer which should be injected into the component like so:

constructor(private sanitizer: DomSanitizer)

The problem I have is that my class that needs the sanitization is a simple typescript class, it is not a component. How do I inject the sanitizer? Or otherwise sanitize this value.

Here's the relevant codes:

Template:

<div class="transition" *ngFor="let transition of state.transitions"
  [style.transform]="transition.transformPosition"
  [style.width.px]="transition.width"></div>

Class:

export class Transition {
  origin: State;
  destination: State;
  conditions: AlphabetSymbol[];

  constructor(origin: State, destination: State) {
    this.origin = origin;
    this.destination = destination;
  }

  get transformPosition() {
    let x = (this.origin.layoutPosition.x + this.destination.layoutPosition.x) / 2,
        y = (this.origin.layoutPosition.y + this.destination.layoutPosition.y) / 2,
        angle = Math.atan(  (this.destination.layoutPosition.y - this.origin.layoutPosition.y)
                          / (this.destination.layoutPosition.x - this.origin.layoutPosition.x)),
        finalString;

    x -= this.origin.layoutPosition.x;
    y -= this.origin.layoutPosition.y;
    angle *= 180 / Math.PI; // Convert to degrees
    finalString = "rotate(" + angle + "deg)translate(" + x + "px," + y + "px)";        

    return finalString;                            
  }

  get width() {
    return this.origin.layoutPosition.distanceTo(this.destination.layoutPosition) - 60;
  }
}

For reference, if I return the plain "transform" value with just a translate or just a rotate, it accepts the string, but combining those is marked as unsafe.

1

There are 1 best solutions below

0
On BEST ANSWER

I managed to solve this by wrapping the unsafe style inside a function defined in the template's parent component.

Template

<div class="transition" *ngFor="let transition of state.transitions"
  [style.transform]="sanitizeStyle(transition.transformPosition)"
  [style.width.px]="transition.width"></div>

Template's Parent (Component)

constructor(private sanitizer: DomSanitizer)
...
sanitizeStyle(unsafeStyle: string): SafeStyle {
  return this.sanitizer.bypassSecurityTrustStyle(unsafeStyle);
}