In Angular how do I get the ngModuleRef for the module I'm in when I want to dynamically create a component?

Viewed 815

Consider a module created like this:

@NgModule({
  imports: [ BrowserModule ],
  providers: [ AdService ],
  declarations: [
    AppComponent,
    AdBannerComponent,
    HeroJobAdComponent,
    HeroProfileComponent,
    AdDirective
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

I want to get the ngModuleRef for the AppModule so that I can pass it in as an option argument to the createComponent function like this:

viewContainerRef.createComponent<AdComponent>(addItem.component,{ngModuleRef:myModuleRef<unknown>})

Is this possible? If so, how do I get the ngModuleRef to do it?

1 Answers

If you are dynamically loading the module, this is how you would do it.

const { AppModule } = await import(`PATH_TO_MODULE_TS`);
const ngModuleRef = createNgModuleRef(AppModule) // createNgModuleRef is from @angular/core

optionally, you can pass an Injector as a second parameter to createNgModuleRef if you need to define providers, or you could also pass an injector in the options of the createComponent method.

Related