Lazy loading is the beautiful feature which Angular provides. We can load the modules only when the user navigates to their routes for the
first time. It will increase the application performance and also will reduce the initial bundle size.
The Angular Router has always supported lazy loading but now in Angular 8, we can dynamically import the lazy-loaded module only when it is needed.
It is promise based and gives you access to the module whenever the module is called.
Let's create a transaction module for demonstrating the angular 8 dynamic EcmaScript imports:
1
2
3
|
ng g c transactions/list
ng g c transactions/detail
ng g c transactions/create
|
This will create a transaction list, detail and create components.
Now let's create a routing module for transactions at location: app/transactions/tranactions.routing.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import { ListComponent } from './list/list.component';
import { DetailComponent } from './detail/detail.component';
import { CreateComponent } from './create/create.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: 'list',
component: ListComponent
},
{
path: 'details',
component: DetailComponent
},
{
path: 'create',
component: CreateComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TransactionsRouting { }
|
Now let's create a module for transactions at location: app/transactions/transactions.module.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TransactionsRouting } from '../transactions/transactions.routing';
import { ListComponent } from './list/list.component';
import { DetailComponent } from './detail/detail.component';
import { CreateComponent } from './create/create.component';
@NgModule({
declarations: [
ListComponent,
DetailComponent,
CreateComponent
],
imports: [
CommonModule,
TransactionsRouting
]
})
export class TransactionsModule { }
|
Now let's create an app routing module at location: app/app.routing.ts
1
2
3
4
5
6
7
8
9
10
11
12
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const appRoutes: Routes = [
{ path: 'transactions', loadChildren: () => import('../app/transactions/transactions.module').then(mod => mod.TransactionsModule) }
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes, { enableTracing: false })],
exports: [RouterModule]
})
export class AppRouting { }
|
Here in the above example, you can see, I'm lazy loading transactions module by using dynamic import syntax. This module will be loaded when a user navigates to transactions route.