首页 > 解决方案 > 如何将 DomSanitizer 作为打字稿中的参数传递给管道?

问题描述

我正在使用管道显示具有以下代码的羽毛图标:

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?

标签: angularangular-pipeangular-dom-sanitizer

解决方案


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

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

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

演示


推荐阅读