Angular-6 Lazy Loading For Noobs!

Intro to the Angular lazy loading with routing!

GP
3 min readJun 9, 2018

Angular provides very clean and easy way to modulerize application using NgModules. But Angular also provides easy way to divide application bundle into chunks based on group of features or routes and reduce initial load time. And the remaining chunks are loaded only when users visits that specific route. Sounds awesome!

So lets try to implement a very basic app which implements Angular-6 lazy loading.

Pre-Requisite

Latest npm version (6.1.0 or above)
Latest angular cli version (6.0.8 or above)

First, lets create new angular app using following angular-cli command

ng new lazy-loading --routing

The “ — routing” flag in above commands, instructs angular-cli to generate routing specific ts files for our new app.
Once all the files are generated and node dependencies are installed, cd into the “lazy-loading” folder and run application in development mode using following command:

ng serve

Once app is running without any error, visit the app url in browser which normally should be

http://localhost:4200/

Now lets create two Angular modules which represent two features of application and will be containing feature specific components, and will be accessed by different urls. Create new modules and module components using following command:

ng generate module admin --routing
ng generate component admin/admin-dashboard
ng generate module staff --routing
ng generate component staff/staff-dashboard

Just like the time we created app, “ — routing” flag in above commands makes sure, routing module files are created for our new modules too. It also does take care of integrating admin.module & admin-routing.module, and staff.module & staff-routing.module.

admin-routing.module and staff-routing.module will be responsible for handling all admin and staff specific routes and should have mappings for route paths to components. .

Now lets start defining our routes.
Add following routes to admin.routing.module.ts.

import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';const routes: Routes = [
{
path: '',
component: AdminDashboardComponent
}
];

Add following routes to staff.routing.module.ts

import { StaffDashboardComponent } from './staff-dashboard/staff-dashboard.component';const routes: Routes = [
{
path: '',
component: StaffDashboardComponent
}
];

In above code samples we bound module specific root path with dashboard components.

And finally we connect our app-routing.module with these two modules using following routes config added to app-routing.module. Notice that in following routes config, we are not binding path to a component, instead we are using “loadChildren” tag, which is given path of the module file followed by “#” (hashtag) and name of the NgModule Class.

const routes: Routes = [
{
path: 'admin',
loadChildren: './admin/admin.module#AdminModule'
},
{
path: 'staff',
loadChildren: './staff/staff.module#StaffModule'
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];

So now Angular knows, which files/chunks to load when specific routes are requested in application.

Lets add following to the app.component.html, so that we can click on links to visit different parts of our application.

<div style="text-align:center"><button routerLink="">Home</button><button routerLink="/admin">Admin</button><button routerLink="/staff">Staff</button><h1>Welcome to {{ title }}!</h1></div><router-outlet></router-outlet>

“router-outlet” tag is where our route views will be rendered.

By this time when you save your files, you should be able to see 3 different chunk files (admin-admin-module.js, main.js, staff-staff-module.js) are being created in logs of “ng serve”. If not seeing logs as given below, try killing and re-running “ng serve”.

chunk {admin-admin-module} admin-admin-module.js, admin-admin-module.js.map (admin-admin-module) 11.3 kB  [rendered]
chunk {main} main.js, main.js.map (main) 12.4 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 8.05 kB [entry] [rendered]
chunk {staff-staff-module} staff-staff-module.js, staff-staff-module.js.map (staff-staff-module) 7.59 kB [rendered]

It means that our application is divided into 3 chunks

  1. Root chunk (app.module)
  2. Admin specific chunk (admin.module)
  3. Staff specific chunk (staff.module)

(If not working try killing ng serve and restarting it)

Once everything is working and compiling as expected, open chrome dev tools / Network tab and reload the page

You will see all the required files are loaded.

Once you click on admin button you will see new network request being made to fetch admin specific chunk and same will happen when you click staff button.

Happy Lazy Loading :)

Check out running version of the app:

https://bnmiprkr.github.stackblitz.io/

Download Code

Check out cooler version of the app:

https://yqniawkn.github.stackblitz.io/

Want to know how to make it look little nicer 4 steps, please check out next post on how to add Angular Material to this project :)

--

--