簡體   English   中英

如何將DomSanitizer作為打字稿中的參數傳遞給管道?

[英]How to pass DomSanitizer as an argument in typescript to a pipe?

我正在使用管道來顯示具有以下代碼的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):未提供'sanitizer'的參數。

然后我嘗試

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

但是管道輸出:

無法讀取未定義的屬性“ bypassSecurityTrustHtml”。

我如何使用Typescript通過管道設置innerHTML?

需要將sanitizer注入組件中的構造函數

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

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

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM