DEV Community


[Done Quick] Easy Lazy loading with Angular 8

nitinja profile image Nitin Jadhav ・1 min read

Here are the steps to quickly add lazy loaded modules (loads only after the user navigates to a specific feature or page):

Note that your app must be arranged as feature modules instead of one big AppModule. Make sure that you have installed latest angular cli with the command npm install -g @angular/cli.

step 1: create a Demo App

ng new MyApp --routing

step 2: Add a feature module and component inside the new module which needs to be lazily loaded

ng g module feature --routing
ng g component MyFeature --module=feature

step 3: In your app.component.html add a link to the lazy module

<a routerLink="/feature">Lazy feature</a>
note that this file also has <router-outlet></router-outlet>

step 4: Add Lazy loading to the main app router file (app-routing.module.ts). Notice the import statement - this is where the magic happens!

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

const routes: Routes = [
    path: 'feature',
    loadChildren: () =>
      import('./feature/feature.module').then(module => module.FeatureModule)

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

step 5: Finally, add lazy routing to feature module routing file (feature-routing.module.ts)

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MyFeatureComponent } from '../my-feature/my-feature.component';

const routes: Routes = [{
  path: '',
  component: MyFeatureComponent

  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
export class FeatureRoutingModule { }

That's it! Run the project with ng serve and click the link in your new app. See the browser console for the lazy loaded module.

Devtools show lazy angular module loading

Discussion (0)

Editor guide