Blog>
Snippets

Lazy Loading a Feature Module

Explain and implement lazy loading for a feature module using Angular's NgModule which can improve the initial loading performance of the application.
const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  },
  //... other routes
];
This route configuration uses the 'loadChildren' property to define a function that imports the feature module file asynchronously. The 'import' call returns a Promise, and once the module is available, it will be loaded by the Angular router when the path 'feature' gets activated.
@NgModule({
  declarations: [],
  imports: [
    //... other imports
    RouterModule.forChild(featureRoutes)
  ]
})
export class FeatureModule {}
Here, we define the FeatureModule by using the NgModule decorator where we import 'RouterModule.forChild'. The 'forChild' method is used to supply the routes that are specific to this feature module, allowing Angular to integrate them with the main application routing when the module is lazily loaded.