How to implement Lazy Loading in Angular

by Sai gowtham2min read
How to implement Lazy Loading in Angular

The Angular CLI is a command line interface tool that can create a project, add files, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.

If you need to update Angular CLI then you can update it easily by using the following commands.

npm install -g @angular/cli
ng serve --open

ng new is used to generate angular boilerplate.

What is Lazy loading?

Lazy loading helps us to download the web pages in chunks instead of downloading everything in a big bundle.

To implement the Lazy Loading in Angular we need to create a routing module and a module.ts file for the component we need to lazy load.

folder structure

In the above image, we have created two files which are posts-routing.module.ts and posts.module.ts.

Now let’s see what we need to code in these two files.


In the above code first we created a routes array with an object containing path and component.

In the line 14 we are passing the routes array as an argument to the RouterModule.forChild method.


Here we added a PostsComponent to the declarations array, that’s it we are done with the child level components.

Now we need to create a new file called app-routing.module.ts on root level of your app it means inside the app folder.



In the app.module.ts file we need to remove the declarations for the components which we would like to lazy load.

This is our final output

lazyloading in angular

Have you seen in the above image we successfully implemented the lazy loading?

Code repository

Happy coding…🤗