Home > Software design >  Angular - Passing dynamic HTML to component as variable
Angular - Passing dynamic HTML to component as variable

Time:11-12

I'm building a component which is basically a menu that reuses some Angular Material mechanisms and I would like to allow the users to add some icons dynamically so they'll be able to add some interactivity like onclick events (for example).

I've set it this way in my component logic (.ts):

@Input() additionalIcons: string;

And there's my template:

<my-component>
  <mat-expansion-panel-header>
    <mat-panel-title>
      <h4>{{ title }}</h4>
    </mat-panel-title>
    <div  [innerHTML]="additionalIcons"></div>
  </mat-expansion-panel-header>
</my-component>

So when I call my component, I would like to be able to pass a set of icons this way when I call it:

<my-component
  param1
  ...
  additionalIcons=`<mat-icon aria-label="Label">settings</mat-icon>`
>
</my-component>

But doing it this way doesn't work because - I believe - that for some security reasons, the HTML is removed. This is the result I get:

enter image description here

I've also tried this way:

ngOnInit() {
    if (typeof this.additionalIcons === "string") {
      this.additionalIcons = this.sanitizer.bypassSecurityTrustHtml(this.additionalIcons);
    }
  }

But the visual result is the same ('settings'appears instead of the icon)

How would you approach this? Thanks for your time!

CodePudding user response:

The answer of DanGo is straightforward. Here is why it doesn't work as you expected.

From https://stackoverflow.com/a/40474494

Angular doesn't process HTML added dynamically, it just adds it verbatim except some sanitization to prevent security issues.

Angular doesn't add web components to the registry so the browser don't know that mat-icon is a component thus it displays nothing.

  • Related