DEV Community

xRdev_38
xRdev_38

Posted on

Lazy Loading in Angular (Modules & Standalone)

Lazy Loading in Angular

Lazy loading lets you load features only when needed, reducing the initial bundle size.


Example with NgModules

In app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

Example with Standalone Components (Angular 15+)

In app.routes.ts:

import { Routes } from '@angular/router';

export const routes: Routes = [
  {
    path: 'admin',
    loadComponent: () =>
      import('./admin/admin.component').then(c => c.AdminComponent)
  }
];
Enter fullscreen mode Exit fullscreen mode

And in main.ts:

import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';

bootstrapApplication(AppComponent, {
  providers: [provideRouter(routes)]
});
Enter fullscreen mode Exit fullscreen mode

Advantages

  • Faster startup
  • Smaller initial bundle
  • Compatible with both Modules and Standalone APIs

Conclusion

Use lazy loading to boost your Angular app’s performance, whether you rely on classic NgModules or the new Standalone Components API.

Top comments (0)