Blog>
Snippets

Implementing Lazy Loading in Angular Modules

Demonstrate how to split the application into feature modules and lazy load them to improve the initial load time on mobile devices.
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)
  }
  // other routes...
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
This is the AppRoutingModule where we define the route for the lazy-loaded module. The 'loadChildren' function returns a promise that resolves to the module.
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 is the definition of a feature module (FeatureModule). This module will be loaded lazily when the user navigates to its route. It includes its own FeatureRoutingModule to define child routes.
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 (FeatureRoutingModule). Here we define the routes for the feature module components. The 'forChild()' method is used for feature modules as opposed to the 'forRoot()' used in the AppRoutingModule.
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-feature',
  templateUrl: './feature.component.html',
  styleUrls: ['./feature.component.css']
})
export class FeatureComponent implements OnInit {
  constructor() { }

  ngOnInit(): void {
    // Component initialization logic
  }
}
This is the FeatureComponent that will be lazily loaded when its route is activated. This component can have its own services, child components etc.