How to lazy load modules in Angular

Lazy loading in Angular improves application performance by loading feature modules only when users navigate to specific routes. As the creator of CoreUI with extensive Angular development experience since 2014, I’ve implemented lazy loading in numerous large-scale applications to reduce initial bundle sizes. The most effective approach uses dynamic imports in route configurations to load modules on demand. This pattern dramatically improves initial load times while maintaining full functionality for all application features.

Use dynamic imports in route configuration to load feature modules only when their routes are accessed.

// app-routing.module.ts
import { NgModule } from '@angular/core'
import { RouterModule, Routes } from '@angular/router'

const routes: Routes = [
  {
    path: 'users',
    loadChildren: () => import('./users/users.module').then(m => m.UsersModule)
  },
  {
    path: 'products',
    loadChildren: () => import('./products/products.module').then(m => m.ProductsModule)
  },
  {
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full'
  }
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

// users/users-routing.module.ts
const routes: Routes = [
  {
    path: '',
    component: UserListComponent
  },
  {
    path: ':id',
    component: UserDetailComponent
  }
]

// users/users.module.ts
@NgModule({
  declarations: [UserListComponent, UserDetailComponent],
  imports: [CommonModule, UsersRoutingModule]
})
export class UsersModule {}

This code sets up lazy loading using the loadChildren property with dynamic imports. When users navigate to /users, Angular dynamically loads the UsersModule and its components. Each feature module has its own routing configuration, creating a hierarchical structure that loads only when needed.

Best Practice Note:

This is the lazy loading architecture we implement in CoreUI Angular templates for optimal performance in enterprise applications. Use Angular CLI’s bundle analyzer to monitor chunk sizes and ensure lazy loading is working effectively across your application modules.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team