How to implement Lazy Loading in Angular?

Here, we will have a look at the Angular Routing Process and how to implement Lazy Loading in Angular.

Before starting with the Angular Routing Process, let’s first understand the Angular Boot Process.

Check the below link on how to create an Angular application.

The entry point for every Angular application is the “main.ts” file.

main.ts file

platformBrowserDynamic() — This part of the line indicates that we are about to boot Angular Application in a browser environment.

bootstrapModule() — This function helps bootstrap our root module taking the root module as its argument.

AppModule — AppModule is our root module which is the entry module for our application, this can be any of the modules in our application but by convention, AppModule is used as the root module.

In our AppModule, we then need to specify the component that will serve as the entry point component for our application. How to specify?

In app.module.ts, we import the entry component (conventionally AppComponent) and supply it as the only item in our bootstrap array inside the NgModule configuration object.

app.module.ts

Step-by-Step Process of Angular Routing

Router Navigation Lifecycle

For every navigation, a series of steps take place before the router renders the new component on the screen. This is Router Navigation Lifecycle.

  1. URL Matching and Redirect Events — Routes Recognized

The router starts by doing a depth-first search through the array of router configuration, and try to match the URL to one of the path properties in the router configuration(applies and redirects along the way).

Router Configuration Array

If the matched path requires lazy loading, it will load at this point.

The Router now emits “Routes Recognized” event to signal that it has found a match for the URL, and a component to navigate.

2. Routes Guards

events — GuardsCheckStart, GuardsCheckEnd

Route Guards are boolean functions that the router uses to determine if it can perform a navigation. As Developers, we use guards to control whether a navigation can occur or not.

The control code for navigation is written in “canActivate” guard. If the logic in “canActivate” guard returns true, the guard passes successfully, otherwise, the guard fails, and the router emits a “Navigation Cancel” event, and aborts the entire navigation.

Other guards include canLoad(should a module be lazy-loaded or not), canActivateChild, and canDeactivate(useful for preventing a user from navigating away from a page, for instance, when filling out a form).

canActivate Guard

The router will run guards every time there is a change to the URL. The canActivate guard is run before any data is fetched for the route. Since there is no reason to fetch data for a route that shouldn’t be activated.

3. Route Resolvers

events — ResolveStart, ResolveEnd

Route Resolvers are functions that we can use to prefetch data during navigation before the router has rendered anything.

Similar to guards, we specify a resolver in the router configuration using the resolve property.

Once the router has matched a URL to a path, and all guards have passed, it will call the resolve method in the class to fetch data. The router stores the result on the service’s object and information can be read by subscribing to it.

Resolvers let us prefetch component data during routing. This technique can be used to avoid partially loaded templates to the user by prefetching any data.

A components template will be visible to the user during OnInit, so fetching any data that needs to be rendered in that lifecycle hook can lead to a partial page load. It’s better to let a page partially load, as it will increase the users perceived performance of the application.

The decision is up to us, whether or not to prefetch the data, but it is recommended to have a partial page load with nice animation instead of using resolvers.

Once the router has processed all resolvers, the next step is to start rendering components using appropriate router-outlets.

4. Activating Routes

events- ActivationStart, ActivationEnd, ChildActivationStart, ChildActivationEnd

Now it’s time to activate components and display them using appropriate <router-outlet>. The router will extract the information it needs about the component from the tree of ActivatedRouteSnapshots.

5. Updating the URL

The last step is to update the URL.

LAZY LOADING

First, you need to create a shared module file. Following is the command to create a new module class.

ng generate module moduleName

Shared Module

Now, add all the required components that you want to lazy load in declarations array. You also need to create a new array called exports and all the components you imported in declarations array. The file should be something like below,

Shared Module after adding components

NOTE: When you create a component by CLI, it will be automatically added to the app.module.ts file, make sure you delete them in the app.module file and add it to the shared module if you want to lazy load that component.

app.module.ts

Now, add your new module in path in your app-routing.module.ts file as follows,

app-routing.module.ts

Now, run the application and check if it working without errors,

Terminal after compilation

Now, when you navigate between normal components and lazy loading components you will see a slight delay in page load because of lazy loading. To overcome this problem, we can add something like below in your app-routing.module.ts file,

Preloading Strategy in the app-routing.module.ts

This will preload the components just before you load them, this will remove that slight delay we faced before.

Things that need to be taken care of while declaring lazy load modules

Care must be taken to avoid any reference to any part of the lazily loaded module such as importing module. Otherwise, there will be a compile-time dependency on that module, and Angular will have to include it in the main bundle, thereby defeating the purpose of lazy loading.

This is about lazy loading, you find the complete project at

If you have any queries, feel free to ask in the comment section.

Thank you.

Hello World, I am an aspiring full-stack web developer and a tech enthusiast.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store