3

I have a simple @NgModule the boostrap 2 components :

// Global module for all Angular Component
@NgModule({
    declarations: Components, // directives, components, and pipes owned by this NgModule
    imports: [BrowserModule, HttpModule, FormsModule],
    providers: Providers,
    bootstrap: [Menu, Main]
})
export class MenuModule { }

I want to store a reference of my Main component bootstraped by my MenuModule. I tried to implement the .then method of bootstrapModuleDynamic(), but I only get the factory of the component.

// Bootstrap of module
platformBrowserDynamic()
    .bootstrapModule(MenuModule)
    .then((menuModule: NgModuleRef<MenuModule>) => {
        var test: ComponentFactory<Main> = (<any>menuModule).bootstrapFactories[0];
    });

Any ideas ?

Christophe Gigax
  • 3,211
  • 4
  • 25
  • 37

1 Answers1

5

I see two ways to get list of bootstraped components:

1) Using ApplicationRef

platformBrowserDynamic()
    .bootstrapModule(MenuModule)
    .then((menuModule: NgModuleRef<MenuModule>) => {
        const appRef = menuModule.injector.get(ApplicationRef);
        const components = appRef.components;      
    });

2) Using ngDoBootstrap method on your module:

@NgModule({
    declarations: [Components, // directives, components, and pipes owned by this NgModule
    imports: [BrowserModule, HttpModule, FormsModule],
    providers: Providers,
    entryComponents: [Menu, Main]
    // bootstrap: [Menu, Main]
})
export class MenuModule {
   ngDoBootstrap(appRef: ApplicationRef) {
     const compRefMenu = appRef.bootstrap(Menu);
     const compRefMain = appRef.bootstrap(Main);
   }
}
yurzui
  • 205,937
  • 32
  • 433
  • 399
  • Thanks ! I choose the first solution. – Christophe Gigax Sep 29 '16 at 14:56
  • How do you load that NgModuleRef and ApplicationRef in the main.ts @ChristopheGigax – Nitin Agarwal Jul 12 '18 at 13:36
  • @ChristopheGigax, can you share me the code please for loading the above procedure. – Nitin Agarwal Jul 12 '18 at 13:40
  • I don't have the code anymore, sorry. It was a long time ago. Maybe you can find the `NgModuleRef` with the `then` method of the `bootstrapModule` method. – Christophe Gigax Jul 12 '18 at 15:12
  • @ChristopheGigax, thanks for your reply. Can you help any manner how you have written that, where in which file like main.ts, or module file. As I have tried it, but both the solution is not working. If possible try to remember and help me. – Nitin Agarwal Jul 13 '18 at 05:12
  • Why don't you store you component instance when it's bootstrap from himself ? Like into the `constructor` of `ngOnInit` ? – Christophe Gigax Jul 13 '18 at 08:41
  • Hello yurzui, why root services shared across `appRef.bootstrap(Menu);` and `appRef.bootstrap(Main);` as singltone service. Why appRef does not create own instance of service for each app? –  Mar 19 '21 at 13:04