Lazy-Loading Feature Modules In Angular

Reading Time: 6 minutes

Before starting the lazy-loading feature module of angular, first, let’s understand what a module is? So, a module is a way to group components, pipes, and services, etc., all together that are related to each other. Module set is group together to form an application. One component can use the data of other modules.

Angular Modules:

In angular, this feature is defined by NgModule. Every application has at least one NgModule class that is the root module of an application. The root module is AppModule and we define it in the src/app/app.module.ts file.

For creating an Angular Module we must use the class decorator @NgModule, this decorator uses a metadata object with properties that define the module. The main properties are:

  • imports: array with other modules that can be use by components it this module.
  • declarations: receives an array of components that are part of the module.
  • exports: define an array of components, directives and pipes that can be use by other modules.
  • providers: declares the services, if it is the root module, the services are available for the entire application.

The basic root structure of the root module looks like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
 declarations: [
   AppComponent
 ],
 imports: [
   BrowserModule,
   AppRoutingModule
 ],
 providers: [], 
 bootstrap: [AppComponent] 
})
export class AppModule { }

As a result, this code indicates that the AppModule class turned into Angular Module with the help of @NgModule Decorator.

Now let’s understand what is a lazy-loading feature module in Angular?

Lazy-Loading feature module:

Angular creates a Single Page Application i.e., all of the components are loaded at once. So, there is a possibility that a lot of unwanted libraries or modules might be loaded as well. For small projects, this would be fine but as the project functionality grows, the time for loading is also increased if everything is loaded at once. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.

Let’s start step-by-step guide :

There are the following steps through which we can set up the lazy-loaded feature module:

1) Set up an app (if you have already created the app, you can skip this step)

First, we have to create the angular app with the help of CLI. We have to write:

ng new angular-lazy-loading --routing

(i) This command will create the angular app called angular-lazy-loading.
(ii) –routing flag generates a file called app-routing.module.ts, which is one of the files we need for setting up lazy loading for our feature module.
(iii) Now move to app by “cd <app-name>” i.e., cd angular-lazy-loading

2) Create the feature module with the help of routing

Next, we need a feature module for a separate routing file named lazy-loading.

To learn more about routing and navigation, you can refer here.

Here, lazy-loading is the name of the feature module. The path for loading the lazy-loading feature modules is also lazy-loading because it is specified with the –route option. Thus, we have to write the command as:

ng generate module lazy-loading --route lazy-loading --module app.module

This creates a lazy-loading folder which consists of the new lazy-loadable feature module LazyLoadingModule defined in the file and the routing module LazyLoadingRoutingModule defined in the lazy-loading-routing.module.ts file. The command automatically declares the Lazy-loadingComponent and imports LazyLoadingRoutingModule inside the new feature module

The routes array is defined in app.module.ts

const routes: Routes = [
  {
    path: 'lazy-loading',
    loadChildren: () => import('./lazy-loading/lazy-loading.module').then(m => m.LazyLoadingModule)
  }
];

Here, the lazy-loading uses the loadChildren followed by function. The import path is the relative path to the module.

3. Add another feature module

Add a new feature module along with the stub component. For that, we have to write the same above command to generate it.

ng generate module lazy-loading2 --route lazy-loading2 --module app.module

Now, the src/app/app-routing.module.ts will be like:

const routes: Routes = [
  {
    path: 'lazy-loading',
    loadChildren: () => import('./lazy-loading/lazy-loading.module').then(m => m.LazyLoadingModule)
  },
  {
    path: 'lazy-loading2',
    loadChildren: () => import('./lazy-loading2/lazy-loading2.module').then(m => m.LazyLoading2Module)
  }
];
4. Set up the UI

Now we have to set up our UI. In the app.component.html, we have to replace the default HTML with a simple custom nav, it helps us to navigate our modules in the browser. The app.component.html will look like this:

<h1>
  {{title}}
</h1>

<button routerLink="/lazy-loading">Lazy-loading-1</button>
<button routerLink="/lazy-loading-2">Lazy-loading-2</button>
<button routerLink="">Home</button>

<router-outlet></router-outlet>

Now to run the application in the browser, write the following command in the terminal:

ng serve

After that, go to the browser and write, localhost:4200, where we see our lazy-loading app with a three-button.

The UI looks like this:

All of the three buttons will works automatically, as they were added through CLI.

5. Imports and route configuration

With the help of the CLI, it automatically adds the routes of the feature module. We already define the rote array in the app-routing.module.ts file, additionally now we only have to add the default path to finish off. We can update it like the following code:

const routes: Routes = [
  {
    path: 'lazy-loading',
    loadChildren: () => import('./lazy-loading/lazy-loading.module').then(m => m.LazyLoadingModule)
  },
  {
    path: 'lazy-loading2',
    loadChildren: () => import('./lazy-loading2/lazy-loading2.module').then(m => m.LazyLoading2Module)
  },
{
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

The first two paths are the routes to the LazyLoadingModule and the LazyLoading2Module. The final entry defines a default route.

6. Inside the feature module

Now move to the first feature module i.e., LazyLoadingModule. If you’re using CLI, then following up the above-mentioned steps so you don’t have to do anything, but if not using the CLI, then include the following code inside the LazyLoadingModule.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { LazyLoadingRoutingModule } from './lazy-loading-routing.module';
import { LazyLoadingComponent } from './lazy-loading.component';


@NgModule({
  declarations: [
    LazyLoadingComponent
  ],
  imports: [
    CommonModule,
    LazyLoadingRoutingModule
  ]
})
export class LazyLoadingModule { }

Along with this, the route-specific feature module file i.e., lazy-loading-routing.module file looks like this:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LazyLoadingComponent } from './lazy-loading.component';

const routes: Routes = [{ path: '', component: LazyLoadingComponent }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class LazyLoadingRoutingModule { }

The path here is set to an empty string because the path in AppRoutingModule is already set to lazy-loading.

The second feature module i.e., LazyLoading2Module will also be configured similarly.

7. Verify lazy loading

There are several ways we can verify that:

(i) Now, after all the code is done, we have to verify that does module is loaded lazily. We can verify this by using chrome developer tools.

In chrome. open the developer tool by using Ctrl+Shift+i and then move to the Network Tab.

After that, now click on either the Lazy-loading-1 or Lazy-loading-2 button. You will see that route has been also according to which button has clicked. For clear understanding first, click on the clear option and then move further.

For eg., if you click on the Lazy-loading-1 button the first time, then you find that:

And when you click on the Lazy-loading-2 button first time, then you will see that:

As result, if you’re able to see that files everything is wired up properly and the feature module is being lazy-loaded.

To test it again, click on the clear option and reload the page by using Ctrl+Shift+R, depending on your platform.

(ii) Second way to verify is:

Run the following command to generate the build:

npm run build

After that, when you run that command, you will find like this:

The above image verifies that a separate chunk is generated for the lazy loading module.

(iii) Another way to verify is to open the dist folder of your project. There you will notice a separate file for the module which uses Lazy Loading.

So, it’s the complete way through which we can implement lazy-loading in our app.

It consists of several disadvantages which are as follows:

Disadvantages
  • Firstly, the extra lines of code, to be added to the existing ones, to implement lazy load makes the code a bit complicated.
  • User experience may be affected. For example, backtracking may not be possible if the page structure is not optimal.
  • Loading a large image with javascript and putting it in the DOM occupies the main thread. This might make the user interface (UI) unresponsive during the decoding process
For source code, you can refer this github:

https://github.com/alkavats1/angular-lazy-loading

Conclusion:

In this blog, we have learned about the lazy loading feature module in angular. We’ve seen what exactly is lazy loading, why we need it, and the step-by-step guide to how we can implement it in our projects. To conclude all this, it helps to minimize the application’s start-up time. It avoids the unnecessary request to the server and consumes less memory because it provides us the feature that we can load our module on-demand.

Written by 

Alka Vats is a Software Consultant at Nashtech. She is passionate about web development. She is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. She is a quick learner & curious to learn new technologies. Her hobbies include reading books, watching movies, and traveling.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading