In v12 you could use the following code to load/import a component dynamically, access its NgModule
through ComponentFactory
and then add it to the DOM using ViewContainerRef
.
const injector: Injector = /* injected */
const cfg: ComponentFactoryResolver = /* injected */
const module = await import('path/to/component/file');
const componentDef = module['MyComponent'];
const cf: ComponentFactory = cfg.resolveComponentFactory(componentDef);
const compModule: NgModuleRef = (cf as any).ngModule;
const container: ViewContainerRef = /*retrieved using @ViewChild*/
container.createComponent(cf, null, injector, compModule)
As of v13 ComponentFactory
(docs) and ComponentFactoryResolver
(docs) are now labeled as deprecated and a new signature has been added to ViewContainerRef.createComponent
which accepts a componentType: Type<C>
as the first argument.
abstract createComponent<C>(componentType: Type<C>, options?: { index?: number; injector?: Injector; ngModuleRef?: NgModuleRef<unknown>; projectableNodes?: Node[][]; }): ComponentRef<C>
So you would now do the following to add a dynamically loaded component to the DOM.
const module = await import('path/to/component/file');
const componentDef = module['MyComponent'];
const container: ViewContainerRef = /*retrieved using @ViewChild*/
container.createComponent(componentDef)
However, the docs for the new signature of ViewContainerRef.createcomponent
show the 2nd optional argument is an object called options
that has an optional property ngModuleRef:NgModuleRef<unknown>
. For which the docs state:
ngModuleRef: an NgModuleRef of the component's NgModule, you should almost always provide this to ensure that all expected providers are available for the component instantiation.
Question
I've struggled to find any example usage of ViewContainerRef.createcomponent
that actually includes a value for ngModuleRef
and with the deprecation of ComponentFactoryResolver
and ComponentFactory
am wondering what the correct/official way to retrieve the module in which the component is declared?
Edit
Just to clarify, i'm interested in whether it's still possible to retrieve the module of a component that's been dynamically loaded using the new method in Angular v13, without explicitly knowing the type of that module?
module
come from? – Halpern