1

I was solving a problem how to dynamically create a component received by API. The solution working for me is

private addComponent(template: string) {
    @Component({template: template})
    class TemplateComponent {}

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

    const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
    const factory = mod.componentFactories.find((comp) =>
      comp.componentType === TemplateComponent
    );

    this.blogAppRef = this.container.createComponent(factory);
}

REF: Angular2 - Dynamic components in content received by API

Now, whenever there this function is called it creates a new ng-component and the components just pile one above another. For now, I use this removal code:

... 
    if (this.blogAppRef) {
        this.blogAppRef.destroy();
    }

    this.blogAppRef = this.container.createComponent(factory);
}

which works fine. But my question is, can this be done better? Are there some significant cons about this solution? (memory/power)

I wasn't able to find how to update such dynamically created component. It would require the newly compiled component to replace the previous one; more precisely replace the internal part of ng-content.

Thanks!

Community
  • 1
  • 1
Peter Matisko
  • 2,113
  • 1
  • 24
  • 47

0 Answers0