Loading

Quipoin Menu

Learn • Practice • Grow

angular / Lazy Loading Modules
tutorial

Lazy Loading Modules

Imagine you have a huge application with 100 features. Loading everything at once would make the initial load slow. Lazy loading is like having a smart library where you only bring out the books people actually ask for – you load modules only when the user navigates to them.

Lazy loading dramatically improves initial load time by splitting your application into chunks that are loaded on demand.

Step 1: Create a Feature Module with Routing
Generate a module with its own routing:


ng generate module admin --routing
# or
ng g m admin --routing
This creates admin.module.ts and admin-routing.module.ts.

Step 2: Create Components for the Module


ng generate component admin/dashboard
ng generate component admin/users
ng generate component admin/settings

Step 3: Define Routes in Admin Routing Module
In admin-routing.module.ts:


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { UsersComponent } from './users/users.component';
import { SettingsComponent } from './settings/settings.component';

const routes: Routes = [
{ path: '', component: DashboardComponent },
{ path: 'users', component: UsersComponent },
{ path: 'settings', component: SettingsComponent }
];

@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AdminRoutingModule { }

Step 4: Configure Lazy Loading in App Routing Module
In app-routing.module.ts, use loadChildren instead of component:


const routes: Routes = [
{ path: '', component: HomeComponent },
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
];

How It Works
When the user navigates to /admin, Angular loads the AdminModule JavaScript chunk dynamically. Subsequent navigation within admin (like /admin/users) uses the already loaded module.
Two Minute Drill
  • Lazy loading loads modules on demand, not at startup.
  • Use `--routing` flag when generating feature modules.
  • Feature module uses RouterModule.forChild() for its routes.
  • In app routing, use `loadChildren` with dynamic import.
  • Improves initial load time and performance.

Need more clarification?

Drop us an email at career@quipoinfotech.com