如何将DomSanitizer作为打字稿中的参数传递给管道?

时间:2018-12-24 09:32:24

标签: angular angular-pipe angular-dom-sanitizer

我正在使用管道显示feathericons,其中包含以下代码:

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

import { icons } from 'feather-icons'; // v4+

@Pipe({ name: 'feather' })
export class FeatherIconsPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) {}

  transform(icon: string, size: number = 18, color: string = 'inherit', float: string = 'inline-end') {
    return this.sanitizer.bypassSecurityTrustHtml(icons[icon].toSvg({
      width: size,
      height: size,
      color: color,
      float: float
    }));
  }
}

如您所见,它使用DomSanitizer。我使用这样的HTML管道:

 <span [innerHTML]="'home' | feather"></span>

工作正常。但是现在我需要通过打字稿来做同样的事情。我试过了:

const span = this._renderer2.createElement('span');
let name = new FeatherIconsPipe().transform('home');
this._renderer2.setProperty(span, 'innerHTML', name);

但是它会引发错误:

  

期望1个参数,但得到0.ts(2554)   feather-pipe.ts(9,15):未提供“消毒剂”的参数。

然后我尝试了

private sanitizer : DomSanitizer = this.sanitizer;
...
let name = new FeatherIconsPipe(this.sanitizer).transform('home');

但是管道输出:

  

无法读取未定义的属性'bypassSecurityTrustHtml'。

如何使用打字稿通过管道设置innerHTML?

1 个答案:

答案 0 :(得分:3)

需要将sanitizer注入组件中的构造函数

  constructor(private _renderer2: Renderer2, private sanitizer: DomSanitizer){

     new FeatherIconsPipe(this.sanitizer).transform('home');

Demo