Angular 2 - Sanitizing transform on SVG

2019-09-11 02:29发布

问题:

On mousemove I want to change the translate of my SVG Element, however that is mot applied and I get the following warning: "WARNING: sanitizing unsafe style value" How can I get this style to be applied?

my-component.js:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-component',
    templateUrl: 'my-component.html'
})

export class MyComponent{
@HostListener('document:mousemove', ['$event'])
  onMouseMove(ev:MouseEvent) {

  this.mouseX = ev.clientX;
  this.mouseY = ev.clientY;

  for( var i = 0; i < this.lines.length - 1; i++ )
  {
    var weight = this.lines[i].weight;

    var translateX = Math.round( ( ( this.mouseX - this.halfWidth ) * weight ) / 7 );
    var translateY = Math.round( ( ( this.mouseY - this.halfHeight ) * weight ) / 7 );

    this.lines[i].translateX = translateX;
    this.lines[i].translateY = translateY;
   }
  }


  lines: [
    { translateX: 0.0, translateY: 0.0, weight: 0.40, x1: 86.69, y1: 1, x2: 98.91, y2: 1 },
    { translateX: 0.0, translateY: 0.0, weight: 0.40, x1: 85.31, y1: 9.67, x2: 98.23, y2: 9.67 }
  ]
}

my-component-html:

<svg id="lines" viewBox="0 0 320.6 542.59">
  <line *ngFor="let line of lines" [attr.style]="{'transform': 'translate('+line.translateX+'px, ' + line.translateY+'px)'}" class="line" [attr.x1]="line.x1" [attr.y1]="line.y1" [attr.x2]="line.x2" [attr.y2]="line.y2"/>
</svg>

回答1:

Try using DomSanitizer:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {}
    transform(style) {
        return this.sanitizer.bypassSecurityTrustStyle(style);
    }
}

your html might look like this:

[style.transform]="'translate('+line.translateX+'px, ' + line.translateY+'px)' | safe"

I don't know what you're trying to do but here is Plunker Example

Also don't forget to add SafePipe to declaration array of @NgModule metadata