Applying Lazy Loading for Angular Modules
Explain and illustrate how to implement lazy loading for Angular modules to improve app loading times.
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// Define routes
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
// NgModule setup
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
This code sets up lazy loading for a feature module within an Angular application. It defines a route configuration that uses the `loadChildren` syntax to dynamically import the `FeatureModule` when the 'feature' path is accessed for the first time. This delays the loading of the module until it is actually required.
// feature.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureRoutingModule } from './feature-routing.module';
@NgModule({
declarations: [
// Your components here
],
imports: [
CommonModule,
FeatureRoutingModule
]
})
export class FeatureModule {}
This is the code for a typical module in Angular which could be lazily loaded. The `FeatureModule` includes its own routing module `FeatureRoutingModule`, which would define child routes for this module. By separating the module like this and only referring to it in the `AppRoutingModule` via `loadChildren`, the `FeatureModule` will be loaded lazily.
// feature-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FeatureComponent } from './feature.component';
const routes: Routes = [
{
path: '',
component: FeatureComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FeatureRoutingModule {}
This is the routing module for the feature module (`FeatureModule`) which will be loaded lazily. It defines `FeatureComponent` as the default component for this module. The `RouterModule.forChild` method is used to declare child routes, which nest under the parent route as defined in the application's main routing module.