0
0
Angularframework~5 mins

Module lazy loading preview in Angular

Choose your learning style9 modes available
Introduction

Lazy loading helps your app load faster by only loading parts when needed. It saves time and data by not loading everything at once.

When your app has many pages or features that users may not visit right away.
To improve initial load speed of your Angular app.
When you want to split your app into smaller chunks for better performance.
If you want to reduce data usage on slow or limited internet connections.
Syntax
Angular
const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  }
];

The loadChildren property uses a function that returns a dynamic import.

This syntax tells Angular to load the module only when the user navigates to the 'feature' path.

Examples
This example lazy loads the DashboardModule when the user visits '/dashboard'.
Angular
const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)
  }
];
This example redirects the empty path to 'home' and lazy loads HomeModule for '/home'.
Angular
const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    loadChildren: () => import('./home/home.module').then(m => m.HomeModule)
  }
];
Sample Program

This Angular routing module sets up lazy loading for the 'products' feature. The ProductsModule will only load when the user visits '/products'. The empty path redirects to '/products'.

Angular
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'products',
    loadChildren: () => import('./products/products.module').then(m => m.ProductsModule)
  },
  {
    path: '',
    redirectTo: 'products',
    pathMatch: 'full'
  }
];

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

// Assume ProductsModule is a separate module with its own routes and components.
OutputSuccess
Important Notes

Lazy loading works best with feature modules that have their own routing.

Make sure the lazy loaded module has its own RouterModule.forChild() setup.

Use browser DevTools Network tab to see when chunks load during navigation.

Summary

Lazy loading delays loading modules until needed, speeding up app start.

Use loadChildren with dynamic import syntax in route definitions.

Helps split app into smaller parts for better performance and user experience.