Angular2 - Dynamically load component from module

后端 未结 2 1795
太阳男子
太阳男子 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

提交回复
热议问题