Angular 9 - 如何在 HTML 页面中动态添加 mat-icon? [英] Angular 9 - How to add a mat-icon dynamically inside HTML page?

查看:55
本文介绍了Angular 9 - 如何在 HTML 页面中动态添加 mat-icon?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 "@angular/core": "~9.1.6", "@angular/material": "^9.2.3" 有一个简单的问题;,,我需要将随机 done 元素添加到 HTML 页面.我尝试将 DomSanitizer 与管道一起使用,但它不起作用.

允许 HTML 标签的管道:

@Pipe({名称:'booleanToIcon'})导出类 BooleanToIconPipe 实现 PipeTransform {构造函数(私有 domSanitizer:DomSanitizer){}变换(值:字符串){返回 this.domSanitizer.sanitize(SecurityContext.HTML, this.domSanitizer.bypassSecurityTrustHtml(value));}}

测试类:

导出类 TableComponent 实现 OnInit {test:string = '<div><h1><mat-icon>done</mat-icon></h1></div>';}

HTML 页面:

测试:<span [innerHTML]="test |booleanToIcon"></span>

但是在 WebBrowser 上生成的 HTML 没有 <mat-icon> 元素,只包含:

done

注意:没有管道,它也返回相同的结果

测试:<span [innerHTML]=test"></span>

如何添加完整的 done HTML 元素以输出 HTML 页面?

解决方案

通过将 MatIcon 组件注册为自定义元素,您可以轻松实现:

ng 添加@angular/elements

app.component.ts:

 构造函数(私人注射器:注射器,){const matIconElement = createCustomElement(MatIcon, { injector: this.injector });customElements.define('mat-icon', matIconElement);}

然后您可以显示自定义的受信任 HTML(使用您描述的管道):

<div [innerHTML]="customHtml |trustHtml"></div>

注意:支持的网络浏览器:

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. I tried to use DomSanitizer with pipe but it doesn't work.

Pipe to allow the HTML tag:

@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:

export class TableComponent implements OnInit {

    test:string = '<div><h1><mat-icon>done</mat-icon></h1></div>';

}

HTML page:

Test:
<span [innerHTML]="test | booleanToIcon"></span>

But the generated HTML on WebBrowser doesn't have the <mat-icon> element, only contains:

<div><h1>done</h1></div>

Note: without pipe, it also returns the same result

Test:
<span [innerHTML]="test"></span>

How can I add the full <mat-icon>done</mat-icon> HTML element to output HTML page?

解决方案

By registering the MatIcon component as a Custom Element you can easily achieve this:

ng add @angular/elements

app.component.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):

<div [innerHTML]="customHtml | trustHtml"></div>

NB: Supported web browsers:

这篇关于Angular 9 - 如何在 HTML 页面中动态添加 mat-icon?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆