[英]Angular 9 - How to add a mat-icon dynamically inside HTML page?
I have a simple problem with "@angular/core": "~9.1.6",
and "@angular/material": "^9.2.3",
, which I need to add random <mat-icon>done</mat-icon>
elements to an HTML page.我有一个简单的问题"@angular/core": "~9.1.6",
and "@angular/material": "^9.2.3",
,我需要添加随机<mat-icon>done</mat-icon>
元素到 HTML 页面。 I tried to use DomSanitizer
with pipe but it doesn't work.我尝试将DomSanitizer
与 pipe 一起使用,但它不起作用。
Pipe to allow the HTML tag: Pipe 允许 HTML 标签:
@Pipe({
name: 'booleanToIcon'
})
export class BooleanToIconPipe implements PipeTransform {
constructor(private domSanitizer: DomSanitizer) {}
transform(value: string) {
return this.domSanitizer.sanitize(SecurityContext.HTML, this.domSanitizer.bypassSecurityTrustHtml(value));
}
}
Test class:测试class:
export class TableComponent implements OnInit {
test:string = '<div><h1><mat-icon>done</mat-icon></h1></div>';
}
HTML page: HTML 页面:
Test:
<span [innerHTML]="test | booleanToIcon"></span>
But the generated HTML on WebBrowser doesn't have the <mat-icon>
element, only contains:但是在浏览器上生成的 HTML 没有<mat-icon>
元素,只包含:
<div><h1>done</h1></div>
Note: without pipe, it also returns the same result注意:没有pipe,也返回同样的结果
Test:
<span [innerHTML]="test"></span>
How can I add the full <mat-icon>done</mat-icon>
HTML element to output HTML page?如何将完整的<mat-icon>done</mat-icon>
HTML 元素添加到 output HTML 页面?
By registering the MatIcon
component as a Custom Element you can easily achieve this:通过将MatIcon
组件注册为自定义元素,您可以轻松实现:
ng add @angular/elements
app.component.ts:应用程序组件.ts:
constructor(
private injector: Injector,
) {
const matIconElement = createCustomElement(MatIcon, { injector: this.injector });
customElements.define('mat-icon', matIconElement);
}
You can then display the custom trusted HTML (using the pipe you described):然后,您可以显示自定义受信任的 HTML(使用您描述的 pipe):
<div [innerHTML]="customHtml | trustHtml"></div>
NB: Supported web browsers:注意:支持 web 浏览器:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.