Blog>
Snippets

Creating a Lazy-Loaded Feature Module

Explain how to create a feature module that's standalone and can be lazy-loaded, improving the initial load time of the application.
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
This code defines the AppRoutingModule with a lazy-loaded route. When the 'feature' path is accessed, the corresponding FeatureModule is loaded asynchronously.
// feature.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { FeatureRoutingModule } from './feature-routing.module';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    FeatureRoutingModule
  ]
})
export class FeatureModule {}
This code snippet represents the FeatureModule which will be lazy loaded. It imports a dedicated FeatureRoutingModule where the feature's components and routes are declared.
// 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 code sets up the FeatureRoutingModule containing the routes specific to the FeatureModule. Each route is associated with a component, which in this case is FeatureComponent.