Angular lazy loading dynamic component Angular lazy loading dynamic component typescript typescript

Angular lazy loading dynamic component


Here's a strategy for dynamically and lazily loading a component. But please beware, I haven't tried it yet!

Get an NgModuleFactoryLoader instance via dependency injection and asynchronously obtain the module containing the component you wish to lazily load. From that, obtain an NgModuleFactory and then obtain an NgModuleRef.

The NgModuleRef will give you:

  • a ComponentFactoryResolver which accepts a Type<T> (from @angular/core)
  • instance() of the module class.

So you can't make a Type<T> from your code to pass to the ComponentFactoryResolver since your code can't depend on T, but the module has access to the T and can provide a Type<T>.

Make the module implement an interface that can return a Type<any> (the component class) and cast NgModuleRef.instance() to that interface. Then use the ComponentFactoryResolver. If that doesn't work for some reason, make the module call ComponentFactoryResolver and return the component directly rather than a Type. Once you have a ComponentFactory you can do dynamic component loading like normal.