Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The procedure for programmatically loading "lazy" modules in an Angular application involves the following steps:

  1. Create a feature module with the lazy-loaded components and export the module's RouterModule.

  2. Configure the routes to lazy load the module using the loadChildren property with the path to the lazy loaded module.

  3. Add an event listener to the router in the app module to handle when a lazy module should be loaded. This can be done using the Router's preloading strategy.

  4. In the event listener, use the load() method to load the lazy module's JavaScript file and then navigate to the lazy module's route when the module is loaded and ready.

  5. Finally, add the lazy loaded module's component to the view where it is needed.

Example code:

// app-routing.module.ts
const routes: Routes = [
  // other routes
  {
    path: 'lazy',
    loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
  }
];

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, PreloadAllModules, Router } from '@angular/router';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(private router: Router) {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationStart) {
        if (event.url === '/lazy' && !this.isLazyModuleLoaded()) {
          this.loadLazyModule(event);
        }
      }
    });
  }

  private isLazyModuleLoaded(): boolean {
    // Check if the lazy module has already been loaded
    return false;
  }

  private async loadLazyModule(event: NavigationStart): Promise<void> {
    const { LazyModule } = await import('./lazy/lazy.module');
    this.router.navigateByUrl(event.url);
  }
}

// lazy.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { LazyComponent } from './lazy.component';

const routes: Routes = [
  {
    path: '',
    component: LazyComponent
  }
];

@NgModule({
  imports: [CommonModule, RouterModule.forChild(routes)],
  declarations: [LazyComponent]
})
export class LazyModule {}