Lazy loading modules in angular enable us to split code into separate modules and load them on demand, this helps developers to have maintainable code and better performance.
By default, angular lazily load modules based on the route path. Lazy loading modules based on the route path suits most cases but sometimes you might want to load a module irrespective of the route path. Some of those cases are as follows.
- Load on button click without route change.
- Load multiple modules for the current route. In such a case one module can be loaded based on the router & others can be loaded manually.
- Dynamically insert components on some criteria.
In this post, I am going to show, how to lazily load modules manually in both imperative & declarative (less imperative) ways. Following the declarative way is important when comes to frameworks since it ensures whether the application has less code and is unit testable.
In terms of frameworks, simply being declarative is leaving the framework to handle things by declaring required syntaxes in the template (as I understand). When I started to learn the differences between imperative and declarative ways, I understand that writing things in the *component.ts file will make you more imperative.
Let’s get started!!
Imperative
The below code loads modules and renders them into the view imperatively.
The reasons which make this imperative are as follows.
- The first thing that makes this code imperative is, manually subscribing to the
loadModule
method. - Next, I see we are compiling the module, registering the injector & resolving the component.
- Appending the component in the
ng-container
using theViewContainerRef
.
Declarative (Less imperative)
Now let’s see the declarative version of the above component and template file. Also, I would say it is less imperative instead of declarative since I am using some RxJS operators & manually loading the module using load
property.
Well, I believe you can see the difference here.
- First thing, lines of code are reduced.
- Removed injection of Compiler.
- Removed manual compiling, injection & component resolving.
- Removed manual appending of the component using ViewContainerRef.
Thanks to Angular!. All the above things comes possible because of the introduction of the ngComponentOutletdirective
. In the above code, I am simply loading the module & resolving the component property after the module loaded successfully.
Wrap it up
Out there, I can see there are many blog posts showing different ways to lazy load non-routable modules in angular and you can choose them based on your application scenarios.
You can find the full source code in this GitHub repo. I hope, you have learned something from this blog as I did.
Thanks for reading. Happy coding. Feel free to contact me if any.
Top comments (0)