Lazy Loaded Routes Angular V8 with Ivy

The following snippet will show you how to setup lazy-loaded routes in Angular v8.0 (and previous versions).

command line
ng new myLazyApp --routing

Now add a link that you can click.

file_type_html app.component.html
<button routerLink="/lazy"></button>
<router-outlet></router-outlet>

Step 1: Create a Module and Component

You lazy-load code in Angular by organizing it into modules. A common practice is to lazy-load each routed page in the app.

command line
ng g module lazy

ng g component lazy-page -m lazy

Step 2: Add Routing to the Lazy Module

file_type_ng_component_ts lazy.module.ts
import { LazyPageComponent } from '../lazy/lazy-page/lazy-page.component';
import { RouterModule } from '@angular/router';

@NgModule({
  declarations: [LazyPageComponent],
  imports: [
    CommonModule,
    RouterModule.forChild([
      { path: '', component: LazyPageComponent }
    ])
  ]
})
export class LazyModule { }

Step 3: Lazy Load it from the App Router

Angular Ivy makes it possible to use dynamic imports - an awesome new web standard - that enables async loading of JS modules.

If using the dynamic import method shown below make sure to enable Angular Ivy in your project. Existing projects can follow this Ivy upgrade guide.

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


const routes: Routes = [
  {
    path: 'lazy',
    loadChildren: './lazy/lazy.module#LazyModule', // use this syntax for non-ivy or Angular 7 and below
    loadChildren : () => import('./lazy/lazy.module').then(m => m.LazyModule), // new dynamic import method
  }
];

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

Q&A Chat