DEV Community

Cover image for How to lazy load modules in Angular with loadChildren
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

How to lazy load modules in Angular with loadChildren

Project: codever - File: app.routing.ts

To lazy load Angular modules, use loadChildren (instead of component) in your AppRoutingModule routes configuration as follows.

import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { PageNotFoundComponent } from './not-found.component';
import { SnippetNotFoundComponent } from './not-found/snippet-not-found.component';

const routes: Routes = [
  {
    path: 'personal',
    loadChildren: () => import('app/personal/personal-bookmarks.module').then(m => m.PersonalBookmarksModule)
  },
  {
    path: 'dashboard',
    loadChildren: () => import('app/user/dashboard/user-dashboard.module').then(m => m.UserDashboardModule)
  },
  {
    path: 'settings',
    loadChildren: () => import('app/user-settings/user-settings.module').then(m => m.UserSettingsModule)
  },
  {
    path: 'public',
    loadChildren: () => import('app/public/public.module').then(m => m.PublicBookmarksModule)
  },
  {
    path: 'my-snippets',
    loadChildren: () => import('app/codelet/codelet.module').then(m => m.CodeletModule)
  },
  {
    path: 'my-codelets',
    redirectTo: 'my-snippets',
  },
  {
    path: 'search',
    loadChildren: () => import('app/search-results/search-results.module').then(m => m.SearchResultsModule)
  },
  {
    path: '',
    redirectTo: 'public',
    pathMatch: 'full'
  },
  {path: '404-snippet', component: SnippetNotFoundComponent},
  {path: '**', component: PageNotFoundComponent}
];


/**
 * See App routing @https://angular.io/docs/ts/latest/guide/ngmodule.html
 */
@NgModule({
  imports: [
    RouterModule.forRoot(
      routes
    )
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {
}
Enter fullscreen mode Exit fullscreen mode

Where a child module might look something like the SearchResultsModule:

const searchResultsRoutes: Routes = [
  {
    path: '',
    component: SearchResultsComponent
  }
];

@NgModule({
  declarations: [SearchResultsComponent],
  imports: [
    RouterModule.forChild(searchResultsRoutes),
    CommonModule,
    CodeletModule,
    SharedModule,
    MatTabsModule,
  ]
})
export class SearchResultsModule { }
Enter fullscreen mode Exit fullscreen mode


Reference:

https://angular.io/guide/lazy-loading-ngmodules


Shared with ❀️ from Codever. πŸ‘‰ use the copy to mine functionality to add it to your personal snippets collection.

Top comments (0)