Angular 13 load/compile dynamic Angular component from HTML string

Viewed 265

I want to load or compile Angular elements as HTML from string into my component.

I am getting HTML string from API as a string and I want to load and render all HTML structural directives from that string.

 let str = `<div>Testing here
  <div *ngFor="let i of [1,2,3,4]">{{i}}</div>
 </div>`;

setTimeout(() => {
  const componentRef: ComponentRef<DynamicComponent> =
    this.createDynamicComponent<DynamicComponent>(
      DynamicComponent,
      this.vc
    );
  componentRef.instance.html = this.sanitizer.bypassSecurityTrustHtml(str);
});

But it output as instead of ngFor loop it simply loads as string.

Load Dynamic HTML
Testing here
{{i}}

Here is sample I tried

Here above is just sample HTML string. It can be anything from server like ngIf or any other inbuilt Angular directives

I have also tried using custom element createCustomElement but in that also I was not able to render Angular directives runtime from string.

Edit 1

Similar thing is working fine for This stackblitz example but If I download and run locally same error.

1 Answers
Related