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

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Neil S