Lazy Loading in Angular – A Beginner's Guide to NgModules
What is Lazy Loading?
Lazy loading is the process of loading components, modules, or other assets of a website as needed.
When your Angular app loads, all app modules are loaded, whether they are required or not. Now, this may not seem like a problem if the app is small, but as its modules grow, it will slow down the entire app.
From the official docs,
By default, NgModules are eagerly loaded, which means that as soon as the application loads, so do all the NgModules, whether or not they are immediately necessary. For large applications with lots of routes, consider lazy loading —a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.
Advantages of Lazy loading:
Lazy loading basics
In order to create lazy loaded modules, execute the below commands:
ng generate m modulea --route a --module app.module
ng generate m moduleb --route b --module app.module
The commands will generate two folders called modulea and moduleb. Each folder will contain its own module.ts, routing.ts and component files.
If you check your app-routing.module.ts you will see the below code for routes:
const routes: Routes = [{path:'a',loadChildren:()=>import('./modulea/modulea.module').then(m=>m.Moduleamodule)},
{path:'b',loadChildren:()=>import('./moduleb/moduleb.module').then(m => m.ModulebModule) },];
const routes: Routes = [{path:'a',loadChildren:()=>import('./modulea/modulea.module').then(m=>m.Moduleamodule)},
{path:'b',loadChildren:()=>import('./moduleb/moduleb.module').then(m => m.ModulebModule) },];
Lazy Loading
To lazy load the modules, go to the app-routing.module.ts file and use loadChildren. You don't need to import the module in the app-routing.module.ts but it will get imported dynamically during runtime.
Here is how the app-routing.module.ts file looks:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{path: 'a', loadChildren: () => import('./modulea/modulea.module').then(m => m.moduleaModule)},
{path: 'b', loadChildren: () => import('./moduleb/moduleb.module').then(m => m.modulebModule)}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Conclusion
In this article, you used lazy loading routes in an Angular application. Lazy loading is an important Angular feature that helps to reduce the initial load time since it loads only the necessary files first.