简体   繁体   中英

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM