Site icon Sails Software Inc

Lazy Load Module in Angular

Lazy Load Module in Angular

Lazy loading is a technique for downloading data on-demand, such as documents, JavaScript, CSS, images, and videos, in small bits.

In Angular, data is loaded in bits rather than larger pieces; we deal with lazy loading using dynamic components and the loadChildren property.

In order to create lazy loading in Angular14, we use the angular app routing module and the main app module class.

The AppRoutingModule is easily obtained from the app-routing.module.ts file, whereas the AppModule class is located in the app.module.ts file.

Create Angular Application:

It serves as both the primary tool and the fundamental building component for all angular applications. To install the most recent version of Angular CLI, enter the following command:

npm install – g @angular/cli

Install New Angular Application:

ng new angular-lazy-load example

Navigate to the project root:

cd angular-lazy-load-example

Generate Angular Module:

The lazy loading that we are building in Angular is entirely dependent on modules, and we need to execute the below command from the command prompt:

ng generate module blog

In the next step, we will generate a few components inside the blog module directory:

ng generate component blog/signin
ng generate component blog/blog-daerails

Lazy Load with LoadChildren

With angular’s loadChildren property, you can lazy load modules. Now we must define the components that must be lazy-loaded within the angular route.

 

Make sure to create an angular-routing.module.ts file and insert the following code.

Setting Up Routes

Ultimately, we have configured lazy-loading in route via dynamic import module.

In this step, we are going to create a separate blog routing, which will handle the lazy-loading for the components associated with it.

ng g m blog/blog –routing

Next, import the components that need to be lazy-loaded for the blog module and pass them in the routes array this way we separate lazy loading components.

Head over to blog/blog-routing.module.ts file and place the following code:

Next, get into the app/blog/blog/blog.module.ts file and insert the given code into it.

We defined the routes for Signin and Blog Details components and inserted within the BlogRoutingModule.

Our next task is to import the blog routing module and components in app/blog/blog.module.ts file. Also, inject the components inside the declarations array.

To test the lazy load functionality, you need to open the Chrome dev tool, navigate to the Network tab and see which files have been loaded:

Here you can see blog module is only loading when we are clicking on the specific route.

The Bottom Line

Eventually, we have seen how to lazy load angular modules. In this tutorial, we shed light on loadChildren service with the angular router to lazy load the modules.

Sails Software Solutions

www.sailssoftware.com

Exit mobile version