0

I´m trying to dynamically import components from a module without explicitly importing all components individual. The module consists of two sub modules with each having a component inside.

I have no clue how to create the components from the list of factories which I get from compileModuleAndAllComponentsSync(ExampleModule).
Here is my code:

app.component.html

<ng-container *ngComponentOutlet="myComponent;
                                    ngModuleFactory: myModule;">
</ng-container>

app.component.ts

import { Component, Compiler } from '@angular/core';
import { ExampleModule } from '@example/example.module';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  private myModule: any;
  private myComponent: any;

  constructor(private compiler: Compiler) {
    const componentList = this.compiler.compileModuleAndAllComponentsSync(ExampleModule);
    // const componentList = this.compiler.compileModuleSync(ExampleModule);
    console.log(componentList);

    this.myModule = null; //<-- What goes here...
    this.myComponent = null; //<--...and here?
  }
}

app.module.ts

 import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { AppComponent } from './app.component';
    import { ExampleModule } from '@example/example.module';


    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        ExampleModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

How can I create the components dynamically from my module?

JohnDizzle
  • 1,268
  • 3
  • 24
  • 51
  • 1
    https://stackoverflow.com/questions/40060498/angular-2-1-0-create-child-component-on-the-fly-dynamically/40080290#40080290 – yurzui Aug 08 '17 at 11:39
  • @yurzui doesn´t work for me, `createComponent()` is no function for cmpRef – JohnDizzle Aug 08 '17 at 11:55
  • Where does @example/example come from? – yurzui Aug 08 '17 at 12:10
  • @yurzui It´s imported from node modules. I already added the two components to `@ngModule.entryComponents` – JohnDizzle Aug 08 '17 at 12:15
  • Then why are you using compiler? Try ComponentFactoryResolver https://stackoverflow.com/questions/40567687/angular-2-insert-a-component-into-the-dom-of-another-component It would be great if you provided plunker – yurzui Aug 08 '17 at 12:22
  • read [Here is what you need to know about dynamic components in Angular](https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e) – Max Koretskyi Aug 08 '17 at 14:53

0 Answers0