Ka Tech
Ka Tech

Reputation: 9457

Angular - Dynamically load html that includes angular markups

In Angular 9+ I can successfully convert a string to a html and then load that that html using innerHtml and bypassSecurityTrustHtml().

My question is it possible to also dynamically load/render the converted html to include and recognise angular/javascript markup language eg *ngIf, handle bars and click events.

Below is the code and stackblitz at the attempt so far but as you can see it doesn't recognise the markup.

https://stackblitz.com/edit/dynamic-angular?file=app/app.component.ts

export class AppComponent implements OnInit {
  text: string = "Hello world";
  content: any;
  constructor(private domSantizer: DomSanitizer) {}

  ngOnInit() {
    let body: any =
      '<div>{{text}}<div><br><button (click)="test()">Test</button>';
    this.content = this.domSantizer.bypassSecurityTrustHtml(body);
  }

  test() {
    alert("It works");
  }
}

Html

<div [innerHTML]="content"></div>

Upvotes: 2

Views: 3183

Answers (1)

errorau
errorau

Reputation: 2334

I have researched and tried many solutions. My research and trial results are below.

html

<div #container></div>

typescript side as below

export class AppComponent implements OnInit {
  @ViewChild("container", { read: ViewContainerRef })
  container: ViewContainerRef;
  constructor(private compiler: Compiler) {}
  text: string = "asdasd";
  ngOnInit() {
    this.addComponent(
      `<div>{{text}}<div><br><button (click)="test()">Test</button>
       `,
      {
        text: "Hello word",
        test: function() {
          alert("It's work");
        }
      }
    );
  }

  private addComponent(template: string, properties?: any = {}) {
    @Component({ template })
    class TemplateComponent {}

    @NgModule({ declarations: [TemplateComponent] })
    class TemplateModule {}

    const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
    const factory = mod.componentFactories.find(
      comp => comp.componentType === TemplateComponent
    );
    const component = this.container.createComponent(factory);
    Object.assign(component.instance, properties);
    // If properties are changed at a later stage, the change detection
    // may need to be triggered manually:
    // component.changeDetectorRef.detectChanges();
  }

demo

some posts I have reviewed

compile dynamic Component

angular-html-binding

I think it makes the most sense :)

Upvotes: 6

Related Questions