Introduction
Lazy Loading is the technique of loading the module or data on demand. It helps us to better the application performance and reduce the initial bundle size of our files. The initial page loads faster and we can also split the application into the logic chunks which can be loaded on demand.
Prerequisites
- Basic knowledge of Angular 2+ version.
- Basic knowledge of Routing.
The step by step process
Let us now understand the steps involved in the demo application.
Step 1
Open the command prompt and write the command for creating a new Angular application. We have an option for routing the module by default.
ng new lazyloadingApp
Step 2
The application is created succussfully. Now, navigate to the application folder and open the application in VS Code.

Step 3
Now, create a new routing module file using the given command. Here --flat helps to create only TypeScript file without containing our own folder.
ng generate module app-routing --flat or ng g m app-routing --flat
Step 4
Now, we are creating two components - home and about - using the below command for demonstration. You can create the components with any name as you like. Here, we are using --module for auto import components to app-routing module.
ng g c home --module app-routing
ng g c about--module app-routing
Step 5
Now, create one more module file for loading on demand. Let us say the name lazy and create one component file with the name employee using the below command.
ng g m Lazy
ng g c Lazy/employee --flat
Step 6
If the above command creates files successfully, then open the app.routing.ts file and import Routes and RouterModule from @angular/router.
Add one constant for defining your routes with the path and component. Here, we used loadChildren load module on the user's demand.
Use RouterModule.forRoot with our routes array.
Now, in your app-routing.module.ts file, add the following code snippet.
- import { NgModule } from '@angular/core';
- import { CommonModule } from '@angular/common';
- import { HomeComponent } from './home/home.component';
- import { AboutComponent } from './about/about.component';
- import { Routes ,RouterModule} from '@angular/router';
- const routes :Routes =
- [
- {
- path:'',component:HomeComponent
- },
- {
- path:'home',component:HomeComponent
- },
- {
- path:'about',component:AboutComponent
- },
- {
- path:'lazyloading', loadChildren : './lazy/lazy.module#LazyModule'
- },
- ]
- @NgModule({
- declarations: [HomeComponent, AboutComponent],
- imports: [
- CommonModule,
- RouterModule.forRoot(routes),
- ],
- exports: [RouterModule]
- })
- export class AppRoutingModule { }


Md RaquibPosted Sep 26, 2019, 1:39 AM
Who commented on this tutorial , have you really run this project or not ? where is the employeelist routing in app-routing file .
Amit Kumar SinghPosted Feb 2, 2019, 11:53 AM
Nice one..Thanks !!
ankit kankarPosted Jan 25, 2019, 8:39 PM
Good explanation....
Pankaj PandeyPosted Jan 25, 2019, 9:40 AM
Nice puneet ...