如何在插入SVG时绕过HTML清理程序

时间:2017-03-01 15:48:06

标签: angular typescript

我正在尝试使用Angular2将带有svg-images的按钮添加到我的Electron应用程序中。我是一个完整的角度初学者,感觉就像现在爬铁丝网一样。

我终于设法让它插入按钮,但它正在消毒svg图像。

如何在没有屠宰的情况下插入图像?

这是我的代码:

import { Component } from '@angular/core';

import { MenuBarButton } from './menu-bar-button';

const WINDOWBUTTONS: MenuBarButton[] = [
  { class: 'closeWindow',
    svg: `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
      <line x1="61.6" y1="962" x2="961.6" y2="62" />
      <line x1="61.6" y1="62" x2="961.6" y2="962" />
    </svg>` },
  { class: 'maximizeWindow',
    svg: `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
      <rect x="62" y="62" class="st0" width="900" height="900" />
    </svg>` },
  { class: 'unmaximizeWindow',
    svg: `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
      <rect x="62" y="293.9" width="668.1" height="668.1"/>
      <polygon points="293.5 62.5 293.5 293.5 730.5 293.5 730.5 730.5 961.5 730.5 961.5 62.5 "/>
    </svg>` },
  { class: 'minimizeWindow',
    svg: `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
      <line x1="62" y1="512.5" x2="962" y2="512.5" />
    </svg>` }
];

@Component({
  selector: 'window-buttons',
  template: `
  <div *ngFor="let btn of buttons" class="button {{btn.class}}" [innerHTML]="btn.svg">
  </div>
  `
})
export class WindowButtonsComponent {
  buttons = WINDOWBUTTONS;
}

编辑:这是管道事物的代码。最初我尝试将它放在一个单独的文件中,但我不确定如何正确地包含它,所以我把它移到我上面发布的同一个文件中。

import { Component } from '@angular/core';

import { MenuBarButton } from './menu-bar-button';

//New Pipe code
import { Pipe } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'safeHtml'})
export class SafeHtml {
  constructor(private sanitizer:DomSanitizer){}

  transform(html: string) { //Error on this line
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}
//end of New Pipe code

const WINDOWBUTTONS: MenuBarButton[] = [
  <<<Same as above>>>
];

//Added '| safeHtml' to the template
@Component({
  selector: 'window-buttons',
  template: `
  <div *ngFor="let btn of buttons" class="button {{btn.class}}" [innerHTML]="btn.svg | safeHtml">
  </div>
  `
})
export class WindowButtonsComponent {
  buttons = WINDOWBUTTONS;
}

我从typscript中得到的错误是:Return type of public method from exported class has or is using name 'SafeHtml' from external module "D:/Dev/angularimgeviewer/node_modules/@angular/platform-browser/src/security/dom_sanitization_service" but cannot be named.

但它似乎仍然输出一个JS文件。当我运行它时,我在控制台中得到了一面文字,似乎以不同的方式说出来:

zone.js:516 Unhandled Promise rejection: Template parse errors:

The pipe 'safeHtml' could not be found ("
  <div *ngFor="let btn of buttons" class="button {{btn.class}}" [ERROR ->][innerHTML]="btn.svg | safeHtml">
  </div>
  ")

0 个答案:

没有答案