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).

Note. This is now the default way to generate lazy routes in Angular, Ivy does not need to be enabled.

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 --routing

ng g component lazy/lazy-page

Step 2: Add Routing to the Lazy Module

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

const routes: Routes = [
  { path: '', component: LazyPageComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
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](/snippets/angular-upgrade-with-ivy).

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 { }

Questions?

Ask questions via GitHub below OR chat on Slack #questions