Angular Lazy Loading Module Example

angular lazy load example

In this tutorial, I am going to create an angular lazy loading module example. This lazy loading concept will help us to imporve the angular application performace as it will load the only components that we are accessing.
Before jumping into lazy load concept, you need to create an angular project with following command “ng new ang-lazyload”. Right after you execute this command you will be asked with couple of questions, type “Y” for angular routing and choose “CSS” for styling your angular application.

Create angular project – Lazy loading example

Now, navigate to “ang-lazyload” folder and then create an empoyee module with the below command, this will be create a module along with routing file.
ng g m feature/employee –routing=true“.
Then create two components called “employee-list” and “add-employee” using the below commands:
ng g c feature/employee/employee-list
ng g c feature/employee/add-employee

Angular lazy load components

Now, i wanted to create a shared module along with header and footer components without router module. We don’t need a router module for this as we are going to utilize this folder components across the application.
ng g m shared
ng g c shared/header
ng g c shared/footer

And I am using bootstrap in this tutorial for decent look & feel so we need to install bootstrap npm package with the command “npm install bootstrap –save-dev
Then open up “angular.json” file and append in styles with the following line and you need to restart your app server to see the changes in browser.

Now, import “employee” and “shared” module in “app.module.ts” file. Update the “app.module.ts” with “app-header”, “router-outlet” and “app-footer”.

Also open up app routing module and update the routes with the below code.

path: 'employee',
loadChildren: () => import('src/app/feature/employee/employee.module').then((m)=> { return m.EmployeeModule})
path: '',
pathMatch: 'full',
redirectTo: 'employee/list',

And open employee routing module and import the employee list and add employee components.

import { EmployeeListComponent } from './employee-list/employee-list.component';
import { AddEmployeeComponent } from './add-employee/add-employee.component';

const routes: Routes = [
component: EmployeeListComponent
component: AddEmployeeComponent

I have updated header, footer, employee list and add employee htmls according to this tutorial.

Run “ng serve -o” it will open your angular project in browser.

Add a Comment

Your email address will not be published. Required fields are marked *