Angular 中插入一段 HTML 代碼的方式大多數(shù)都會(huì)采用管道的方式實(shí)現(xiàn),下面是實(shí)現(xiàn)思路。
- 新建一個(gè)管道
ng g pipe tohtml
裝飾器中標(biāo)記了管道名稱
@Pipe({
name: "tohtml",
})
- 構(gòu)造函數(shù)中注入Dom 消毒劑
constructor(
private _sanitizer: DomSanitizer
) { }
- 在實(shí)現(xiàn)函數(shù)中完成自定義的轉(zhuǎn)換
transform(value: string, args?: number): SafeHtml {
let temp = '<b>' + value + '</b>';
this._sanitizer.bypassSecurityTrustHtml(temp); // 標(biāo)記這是一段可信的HTML
}
- 插入 HTML 的用法
<span [innerHTML]="content | tohtml"></span>