Angular 2 - SVG的消毒变换

时间:2017-04-26 08:12:48

标签: angular typescript svg

在mousemove上我想改变我的SVG元素的翻译,但是这是mot应用的,我得到以下警告: "警告:消毒不安全的风格价值" 如何才能应用此样式?

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 }
  ]
}

我的组分-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 个答案:

答案 0 :(得分:1)

尝试使用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);
    }
}

你的html可能如下所示:

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

我不知道你要做什么但是 Plunker Example

另外,不要忘记将SafePipe添加到declaration元数据@NgModule数组