angular - 如何将 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?
解决方案
需要注入sanitizer
到组件中的构造函数
constructor(private _renderer2: Renderer2, private sanitizer: DomSanitizer){
new FeatherIconsPipe(this.sanitizer).transform('home');
推荐阅读
- server - 我正在使用 Windows 10 并尝试安装 BizTalk server 2016 62 位,但出现此错误
- grid-search - 网格搜索适用于 TFF 和 FL。?
- bash - Shell 脚本根据文件命名模式合并多个 CSV 文件
- r - 加入数据框 R 并重复值
- excel - 获取选定范围的第 N 列值
- node.js - Express.js 在路由未知的情况下忽略 SyntaxError
- r - 使用“exams2moodle”调整大型公式的大小
- excel - 将大于逻辑应用于已自动过滤的行
- sas - SAS 宏引用未解析
- css - CSS 通过水平溢出其父级来强制文本适合特定高度