Lazy Loading pattern in Angular ( concept and implementation )

Jihen Barhoumi
3 min readNov 18, 2022

--

When we build large and complex applications, it is important to structure the components in modules. Each module is dedicated to a specific feature. Therefore, each module contains components of that feature. For example, if you are building a management system, you can have a module for users’ management, a module for tasks’s management, etc.

Lazy loading is a design pattern offered in angular to help you build this modular architecture in a way that optimizes the performance of your app.

By default, when you launch your Angular app, all the routes, resources, and components are loaded at the same time which is called eager loading. If your app is small, this won’t affect its performance much but when your app gets bigger, this approach becomes a problem.

Lazy Loading allows your app to only load the routes of the called module. So if you have components inside a module that you have created, then, only the routes of these components will be loaded at a time of a request and not all the routes of your whole project which helps optimize the time response of your app.

Let’s implement it!

  1. Create a module

To create a module, inside your angular project type this command. In my case, I created a module called profiles.

You will see a new module has been created inside your app folder.

2. Adding module routes to app routing

Inside the file: app-routing.module.ts add the module route definition as follows :

With that line, we told Angular that once we have /profiles written in any URL then it should upload only its components.

3. Create a component inside your module

Use the command as follows. In my case, I created a component called users. Make sure to put your module’s name first then the components name!

4. Add the component’s routes to your module

Inside the module’s routing file, add your component route as follows :

You can do the same steps to create other modules with other components. In our case whenever we type /[module path]/ [component path] for example /profiles/users, in the URL, only the required resources of the module profiles will load.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (1)

Write a response