DEV Community

queencykoh
queencykoh

Posted on • Updated on

Lazy Load a Feature Module

By default, feature modules are eagerly loaded, this means that modules and all its components will load at the initial render of the application.

See my previous post to know more about module and how to create a feature module in Angular.

Setup App Routing Module

To lazy load a feature module, go to app-routing.module.ts

If you do not have the App Routing Module just yet, you can generate it by using the command ng generate module app-routing with --flat to put the file in src/app instead of its own folder and --module=app to tell the CLI to register it in the imports array of the AppModule.

In your app-routing.module.ts, add a routes constant to define your routes, each Route object should have a path property which defines the URL path of your module and loadChildren to import your module dynamically and then pass the routes as an argument in the RouterModule.forRoot() in your imports array.

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


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


imports: [RouterModule.forRoot(routes)],
Enter fullscreen mode Exit fullscreen mode

Open app.component.html and replace the contents with <router-outlet></router-outlet> which works as a placeholder to load components dynamically.

Setup the Feature Module Routes

Generate a new component in the Transactions Module

ng generate component transactions/TransactionsComponent
Enter fullscreen mode Exit fullscreen mode

Go to transactions.module.ts and add a routes constant to define your routes, the Route object should have a path and component properties which is the name of your component, and optionally you can add child routes which you can define in the children properties. In your imports array, instead of forRoot, you will have to use the forChild and pass routes as the argument.

const routes: Routes = [
{
    path: '',
    component: TransactionsComponent,
    children : [
      {
        path: '',
        component: TransactionListComponent,
      }
    ]
  }
];


imports: [RouterModule.forChild(routes)]
Enter fullscreen mode Exit fullscreen mode

Improve Code by Using async await

Add await before import(...) then enclose it with a parenthesis and reference .TransactionsModule directly and lastly mark the function with async

const routes: Routes = [
  {
    path: 'transactions',
    loadChildren: async () => (await import('./transactions/transactions.module')).TransactionsModule
  }
];
Enter fullscreen mode Exit fullscreen mode

Top comments (0)