Implement Lazy Loading with Mat Tabs in Angular

Shubham Kansal
Nerd For Tech
Published in
7 min readApr 20, 2021

What is Lazy Loading?

Lazy loading helps us to download the web pages in chunks instead of downloading everything in a big bundle.

To implement the Lazy Loading in Angular we need to create a routing module and a module.ts file for the component we need to lazy load.

Project Setup

Here, we set up our project. We will be using the Angular CLI (ng) utility throughout in this article.

Run the following command to install the new project:

ng new Lazy-Loading-Mat-Tabs

Creating the components

Now, we will create our components.

  • To create the Header component, run the following command:
ng g c header 

The ng tool has a plethora of commands to use to make development easy and stress-free. Here we used the shortcut notation of ng generate component.

  • To create the Footer component, run the following command:
ng g c footer
  • To create the Home component, run the following command:
ng g c home

NOTE: create home.module.ts and home.routing.ts to implement the lazy loading. Home component will invoke only when it was loaded.

  • To create the About-us component, run the following command:
ng g c about-us

NOTE: create about-us.module.ts and about-us.routing.ts to implement the lazy loading. About-Us component will invoke only when it was loaded.

  • To create the Contact-us component, run the following command:
ng g c contact-us

NOTE: create contact-us.module.ts and contact-us.routing.ts to implement the lazy loading. Contact-Us component will invoke only when it was loaded.

  • To create the Cars component, run the following command:
ng g c cars

NOTE: create cars.module.ts and cars.routing.ts to implement the lazy loading. Cars component will invoke only when it was loaded.

  • To create the Bikes component, run the following command:
ng g c bikes

NOTE: create bikes.module.ts and bikes.routing.ts to implement the lazy loading. Bikes component will invoke only when it was loaded.

When you create components by CLI, they will be automatically added to the app.module.ts file. Your app.module.ts file will now look like this:

app.module.ts

Install Angular Material

Use the Angular CLI’s installation schematic to set up your Angular Material project by running the following command:

ng add @angular/material

when you run the following command then import MatTabsModule and MatToolbarModule in the app.module.ts file.

app.module.ts

Creating a lazy-loaded module

We have actually created our lazy-loaded modules above, here we will implement routing for each of the modules.

Home module

As we noticed above during its creation, two modules were created, home.routing.module.ts and home.module.ts.

home.routing.module.ts holds the routes of the module and it is imported in the imports array of home.module.ts.

We will configure our routes in home-routing.module.ts, by inserting objects inside the routes array:

// src/app/home/home-routing.module.ts
...
const routes: Routes = []
...

The routes: Routes array is used to define all the possible router states an app could be in. It takes an object with two basic properties: path and component.

Insert the following inside it:

// src/app/home/home-routing.module.ts
...
import { HomeComponent } from './home.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
}
];
...

Here, we used an empty path to denote default/index route. We imported HomeComponent, so that we can assign it to the component property in the routes array. The @angular/router uses the component property to know which component to load on the browser DOM.

Insert the following in the home.module.ts :

// src/app/home/home.module.ts
...
import { NgModule } from '@angular/core';
import { HomeComponent } from './home.component';
import { HomeRoutingModule } from './home.routing';
@NgModule({imports: [HomeRoutingModule],
providers: [],
declarations: [HomeComponent]
})
export class HomeModule {}
...

About-Us modules

We will do the same thing as we did above. import the About-uscomponent and configure the routes:

// src/app/about-us/about-us-routing.module.ts
...
import { AboutUsComponent } from ./about-us.component';
const routes: Routes = [
{
path: "",
component: AboutUsComponent
}
]
...

configure the about-us.module.ts

// src/app/about-us/about-us.module.ts
...
import { NgModule } from '@angular/core';
import { AboutUsComponent } from './about-us.component';
import { AboutUsRoutingModule } from './about-us.routing'
@NgModule({
imports: [AboutUsRoutingModule],
providers: [],
declarations: [AboutUsComponent]
})
export class AboutUsModule {

}
...

we will do the same for all other components which are Cars, ContactUs, and Bikes.

Lazy loading the new module

We are done with our feature modules. Now, we set up the parent module, app.module.ts.

As we already made individual module.ts files for all respective components. So, we need to remove the declared components from app.module.ts. Updated app.module.ts file will look like this:

app.module.ts

OK, we now create routes variable that will hold our routes array, just like we saw in our feature modules:

app-routing.module.ts

So, here we made Home component the default route by using the empty path:"". Looking at the next routes, you'll notice something strange there, there is an odd-looking syntax with loadChildren, with a module name. These routes are the routes we want to be lazy-loaded and were set up in feature modules:

  • HomeModule
  • AboutUsModule
  • ContactUsModule
  • CarsModule
  • BikesModule

The loadChildren property is how we tell Angular to lazy load a module. The first part before the => points to the relative path of the feature module. The second part will be the class name of the feature module.

This is how feature modules are lazy-loaded in Angular:

loadChildren: () =>import(PATH_TO_FEATURE_MODULE).then((m) => m.FEATURMODULE_CLASS_NAME)

There are a few important things to note here:

  1. The loadChildren property is used instead of component.
  2. We defined not only the path but, also the name of the feature module class.

Lazy loading the modules using Mat Tabs

Angular Material tabs organize content into separate views where only one view can be visible at a time. Each tab’s label is shown in the tab header and the active tab’s label is designated with the animated ink bar. When the list of tab labels exceeds the width of the header, pagination controls appear to let the user scroll left and right across the labels.

The active tab set when the user selects one of the tab labels in the header.

Configure the app.component.ts by providing the interface TabItems having a label and the route as a member of that interface. Create tabsan array of TabItems and provide the label and the router links.

app.component.ts

Configure the app.component.Html by using the mat-tab-nav-bar to use the router links and replace the existing app.component.html with the following code :

routerLinkActive will help to activate the selected component.

Configure the routes

This is the final stage, at this point, you have finished setting up the modules for all the components you want to lazily load and their separate routes. You have to tell your main app routing module that these routes should be lazily loaded. copy the code block below into your app-routing.module.ts file:

Here you tell Angular it should be loaded lazily by specifying loadChildren in the place of components in an eager loading situation. Everything is completely setup, it is time to run your application:

ng serve

You will see that while bundling up the application, it is now split into those modules we created.

Testing our App

Now, we have our app all set up and all our features modules correctly implemented. We need to test the app, to see them in action.

If you noticed in your terminal, there are extra code bundles generated apart from the normal bundles:

normal bundles

Angular generated extra bundles: aboutus.module.chunk.js ,bikes.module.chunk.js ,cars.module.chunk.js , contact-us.module.chunk.js ,home.module.chunk.js.These are the feature modules we configured to be loaded on demand. These extra module chunks will be loaded when either of the routes /about-us and /home is navigated to.

Navigate to http://localhost:4200 your browser.

And It’s done ✅ . Our application is ready to load components through lazy loading.

The source code is available on GitHub.

Final words

I hope that you had as much fun coding this as I did while writing this code. Now you know how to load components with lazy loading. With this knowledge, we can reduce the main bundle size, and make the experience better for users.

Thanks for reading! 👍

--

--

Shubham Kansal
Nerd For Tech

I am an aspiring full-stack web developer and a tech enthusiast.