Angular2 - Dynamically load component from module

后端 未结 2 1789
太阳男子
太阳男子 2020-12-07 02:25

in my angular app I have the following:

export class MyComponent {
    subcompPath = \"path-to-subcomp#SubcompClassName\";
    @ViewChild(\"placeholder\", {          


        
相关标签:
2条回答
  • 2020-12-07 02:58

    Update:

    If you want to use it together with aot compilation you should manually provide Compiler like

    export function createJitCompiler () {
       return new JitCompilerFactory([{useDebug: false, useJit: true}]).createCompiler();
    }
    ...
    providers: [
      { provide: Compiler, useFactory: createJitCompiler}
    ],
    

    Example

    Old version

    It might help you:

    this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
          .then(({moduleFactory, componentFactories}) => {
            const compFactory = componentFactories
               .find(x => x.componentType === DynamicComponent);
            const cmpRef = this.placeholderRef.createComponent(compFactory, 0);
    

    See also

    • related answer with example
    • How to use variable to define templateUrl in Angular2
    • sample code from angular2 source code
    0 讨论(0)
  • 2020-12-07 03:01

    Based on yurzui's answer I've come to the following code:

    export class MyComponent {
        subcompPath = "path-to-subcompMODULE#SubcompClassName";
        @ViewChild("placeholder", { read: ViewComponentRef }) placeholderRef: ViewComponentRef;
    
        /* Constructor where Compiler, ComponentFactoryResolver are injected */
    
        loadSubcomponent() {
            let [modulePath, componentName] = this.subcompPath.split("#");
            (<any>window).System.import(modulePath)
                .then((module: any) => module["default"])  // Or pass the module class name too
                .then((type: any) => {
                    return this._compiler.compileModuleAndAllComponentsAsync(type)
                })
                .then((moduleWithFactories: ModuleWithComponentFactories<any>) => {
                    const factory = moduleWithFactories.componentFactories.find(x => x.componentType.name === componentName); // Crucial: componentType.name, not componentType!!
                    let componentRef = this.placeholderRef.createComponent(factory, 0);
                });
        }
    }
    
    0 讨论(0)
提交回复
热议问题