May 25, 2020

Lazy loading modules in Angular

Lazy loading allows to load chunks of files on demand and not at that time of initial load of the application, provides a major boost in performance in large Angular apps.

More often that not it is referred as to lazy load components but basically it’s the entire module which is lazy loaded instead of the individual component. So in order to lazy load certain section of your app they need to be a separate feature module and not part of the app module

Below are the steps that must be followed in order to implement lazy loading:

  • Create a  new feature module
  • Add the components that need to lazy loaded inside the new feature module
  • Create the routes in the feature module
  • Remove the reference of the new feature module from the Imports section in main app.module.ts file. This is so that the feature module is not Eagerly loaded along with the entire app
  • Create the route for the components of the feature modules
  • Instead of passing on the component we will use the LoadChildren attribute to pass on the string path of the module file followed by hashtag symbol and the class name used for the feature module.
  • Create the router link which will load the desired component

Here we added a sample feature module Lazy-Posts and its child component Posts which will be lazy loaded.

Feature module for lazy loading

Now that we have our module and component in place, we need to create the routes in lazy-posts.module.ts file so that our posts component can be loaded once it is requested.

Adding routes in feature module

The next step to lazy load this module is to remove it from the main module file and then create the lazy routes for it.

Route for the feature module

The module file is referenced here via its relative path from the app-routing.module.ts file + # + class name.

We have wired up the route to be lazy loaded but still there is no link in our app which loads up the link. Lets quickly add it to complete the setup

Router link for the Posts component

That’s it. The post module will now be loaded only once Lazy Posts link is clicked, thus avoiding the need to load it in the start in case no one actually visits that page.

 Initialially loaded files

Lazy loading module in angular

Like the post? Give a read to the Routing Guide on StackUp!

Leave a Reply

Your email address will not be published. Required fields are marked *