1

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 class="additional-icons" [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!

Timtim
  • 324
  • 8
  • 18
  • Did you solve how to dynamically add the MatIcon component with attributes? I need add the svgIcon attribute to the component to load the right icon, but I don't know how to do that with ViewContainerRef or the resolveComponentFactory – Jiren Feb 10 '22 at 16:14
  • I finally used a *ngFor directive in my template that binds to my icons array (ie: ['add', 'settings']) and for each, generates a with the right icon – Timtim Feb 10 '22 at 19:05

1 Answers1

1

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.

serrulien
  • 695
  • 4
  • 14