Dynamic import NgModule in Angular

How to lazy-load NgModule and Component by using routing, everyone knows. But sometimes you need to lazy load NgModule without routing.
First of all, we need to create NgModule and import it to AppModule, like you usually do it, in order to make sure that you did everything right.
For showing more clearly how it works I decided to create dynamic.component.ts and import it to dynamic.module.ts.
After that we need to create in app.component.html two buttons (load / clear) and ng-template for our dynamic.component.ts (in my previously article I showed how to dynamic load Angular Components).
And update app.component.ts:
- @ViewChild — matching with #container.
- function loadModule() — import dynamic.module.ts.
- createNgModuleRef — create and load dynamic.module.ts.
- ComponentRef — create component.
Function clearComponent() just remove component from container.
Don’t forget to remove DynamicModule from imports in AppModule.
If you do all correctly, you can see result like this.

PS. Angular version 13 and later are using simplicity syntax, for oldest version you need to see documentation.