如何将 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);
但它抛出错误:
Expected 1 arguments, but got 0.ts(2554)
feather-pipe.ts(9, 15): An argument for 'sanitizer' was not provided.
然后我试了
private sanitizer : DomSanitizer = this.sanitizer;
...
let name = new FeatherIconsPipe(this.sanitizer).transform('home');
但是管道输出:
Cannot read property 'bypassSecurityTrustHtml' of undefined.
如何使用 typescript 设置内部 HTML 和管道?
需要将 sanitizer
注入组件中的构造函数
constructor(private _renderer2: Renderer2, private sanitizer: DomSanitizer){
new FeatherIconsPipe(this.sanitizer).transform('home');
我正在使用管道显示 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);
但它抛出错误:
Expected 1 arguments, but got 0.ts(2554) feather-pipe.ts(9, 15): An argument for 'sanitizer' was not provided.
然后我试了
private sanitizer : DomSanitizer = this.sanitizer;
...
let name = new FeatherIconsPipe(this.sanitizer).transform('home');
但是管道输出:
Cannot read property 'bypassSecurityTrustHtml' of undefined.
如何使用 typescript 设置内部 HTML 和管道?
需要将 sanitizer
注入组件中的构造函数
constructor(private _renderer2: Renderer2, private sanitizer: DomSanitizer){
new FeatherIconsPipe(this.sanitizer).transform('home');