How to render a dynamic template with components in Angular2

前端 未结 2 1771
滥情空心
滥情空心 2020-12-16 01:00

I\'ve tried many stackoverflow options like Load existing components dynamically Angular 2 Final Release.

What i want to do is get a html page with a ajax request an

相关标签:
2条回答
  • 2020-12-16 01:21

    Problem solved Thanks to Yurzui,

    https://plnkr.co/edit/TAbupH4si62x10QZ7xuc?p=preview

    The generic HTML outlete from a different post (Angular 2.1.0 create child component on the fly, dynamically) can be used to render templates with custom directives in them.

    Don't forget to import a module with all the custom components that you want to render!

    export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
    const cmpClass = class DynamicComponent {};
    const decoratedCmp = Component(metadata)(cmpClass);
    
    // Import the module with required components here
    @NgModule({ imports: [CommonModule, RouterModule, SharedModule], declarations: [decoratedCmp] })
    class DynamicHtmlModule { }
    
    return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
       .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
        return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
      });
    }
    
    0 讨论(0)
  • 2020-12-16 01:26

    I made tiny changes for using my own components (such as HomeComponent) at @Yurzui and @Linksonder 's solutions. https://plnkr.co/edit/27x0eg?p=preview

    It's basically adding AppModule to DynamicHtmlModule as additional import inside of createComponentFactory().

    @NgModule({ imports: [AppModule, CommonModule, RouterModule, SharedModule], declarations: [decoratedCmp] })
    class DynamicHtmlModule { }
    

    And exports our own components at AppModule

    @NgModule({
      ...
      exports: [HomeComponent, AboutComponent],
      ...
    })
    export class AppModule { }
    
    0 讨论(0)
提交回复
热议问题