Lazy-load Non-Routable Modules with Components in Angular 13+

Valentyn Yakymenko
2 min readFeb 15, 2022

--

Photo by Lukasz Szmigiel on Unsplash

After updating Angular version to 13+ in our project, I realised that we need to update our lazy loading mechanism for non-routable modules with components and services. Here is a tutorial on how to do this.

Issue

I will provide you a real-world example in real application.

We have a grid that represent a widgets like in BI tools. Each of this widget depending on its type has it’s own unique components, services and other modules. Our users have a different access rights to the widgets and they need to load them, only when they viewing the grid which contain widgets or trying to add a new widget in it.

Solution

Firstly, lets create a parent component where we will render our widget depending on a widget type:

Now we need to create an example of a unique widget with it’s own component, service and module:

All right, we have a parent widget container component and table widget example with a list of rows. Now let’s create our lazy-load service, that will use in order to load and render for widgets per widget type:

In our LazyLoadWidgetService we loading our WidgetTableModule for our widget config with type table . After module load we creating reference to it with injector via createNgModuleRef . Then we simply creating component with createComponent method.

Notes

You can easily create more modules with more components and dependencies in this example and add them to the widgetsList . Then depending on a widget type as a key in widgetsList service will load for you a proper module with component and it’s dependencies.

Conclusion

Thanks for reading, hopefully you found this article useful for yourself!

Follow me on Medium or Twitter to read more about Front End, Angular, React and BI!

--

--

Valentyn Yakymenko

Front-end Architect at Codeminders | Passionate about web performance optimization. | Code hard, learn more.