DEV Community

Krishna Bhamare
Krishna Bhamare

Posted on

Lazily load Angular Modules.🤠

Lazy Loading

a. When the modules are loaded on-demand, then it is called lazy loading. It is loaded by using loadChildren property in route configuration. In lazy loading, modules are loaded asynchronously. These modules must not be imported in application module otherwise they will be eagerly loaded.
b. In route configuration loadChildren property is used as following.

const routes: Routes = [
   {
    path: 'country',
        loadChildren: () => import('./country/country.module').then(mod => mod.CountryModule)
   },
   ------
]; 
Enter fullscreen mode Exit fullscreen mode

c. If the application size is growing and there are many feature modules then loading all feature modules eagerly will make application slow. What we can do, is we can load a feature module when it is requested. Such type of module loading is called lazy loading.

Now find the steps to perform lazy loading of feature modules in the previous application which is using eager loading.
Step-1: In route configuration of feature modules, change the parent path as empty string ("").
Module and routing module for feature 1:
country-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CountryComponent }  from './country.component';
import { CountryListComponent }  from './country-list/country.list.component';

const countryRoutes: Routes = [
    { 
      path: '',
          component: CountryComponent,
          children: [ 
        {
          path: 'country-list',
          component: CountryListComponent
        }  
      ]
    }   
];

@NgModule({
  imports: [ RouterModule.forChild(countryRoutes) ],
  exports: [ RouterModule ]
})
export class CountryRoutingModule { }
Enter fullscreen mode Exit fullscreen mode

country.module.ts

import { NgModule }   from '@angular/core';
import { CommonModule }   from '@angular/common';
import { ReactiveFormsModule }    from '@angular/forms';
import { CountryComponent }  from './country.component';
import { CountryListComponent }  from './country-list/country.list.component';
import { CountryService } from './services/country.service';
import { CountryRoutingModule }  from './country-routing.module';

@NgModule({
  imports: [     
        CommonModule,
    ReactiveFormsModule,
    CountryRoutingModule
  ], 
  declarations: [
    CountryComponent,
    CountryListComponent
  ],
  providers: [ CountryService ]
})
export class CountryModule {
  constructor() {
    console.log('CountryModule loaded.');
  }
} 
Enter fullscreen mode Exit fullscreen mode

Module and routing module for feature 2:
person-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PersonComponent }  from './person.component';
import { PersonListComponent }  from './person-list/person.list.component';

const personRoutes: Routes = [
    { 
      path: '',
          component: PersonComponent,
      children: [ 
        {
           path: 'person-list',
           component: PersonListComponent
        }
      ]
    }  
];

@NgModule({
  imports: [ RouterModule.forChild(personRoutes) ],
  exports: [ RouterModule ]
})
export class PersonRoutingModule { }

Enter fullscreen mode Exit fullscreen mode

person.module.ts

import { NgModule }   from '@angular/core';
import { CommonModule }   from '@angular/common';
import { ReactiveFormsModule }    from '@angular/forms';
import { PersonComponent }  from './person.component';
import { PersonListComponent }  from './person-list/person.list.component';
import { PersonService } from './services/person.service';
import { PersonRoutingModule }  from './person-routing.module';

@NgModule({
  imports: [     
    CommonModule,
    ReactiveFormsModule,
    PersonRoutingModule
  ], 
  declarations: [
    PersonComponent,
    PersonListComponent
  ],
  providers: [ PersonService ]
})
export class PersonModule { 
  constructor() {
    console.log('PersonModule loaded.');
  }
}
Enter fullscreen mode Exit fullscreen mode

Step-2: Use loadChildren property to load feature modules in application routing module i.e. AppRoutingModule.
app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddressComponent } from './address.component';
import { PageNotFoundComponent } from './page-not-found.component';

const routes: Routes = [
   {
      path: 'country',
      loadChildren: () => import('./country/country.module').then(mod => mod.CountryModule)
   },
   {
      path: 'person',
      loadChildren: () => import('./person/person.module').then(mod => mod.PersonModule)
   },
   {
      path: 'address',
      component: AddressComponent
   },
   {
      path: '',
      redirectTo: '',
      pathMatch: 'full'
   },
   {
      path: '**',
      component: PageNotFoundComponent
   }
];

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

Step-3: Remove all references of feature modules from application module i.e. AppModule.
app.module.ts

import { NgModule }   from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import { AddressComponent }  from './address.component';
import { PageNotFoundComponent }  from './page-not-found.component';
import { AppRoutingModule }  from './app-routing.module';

@NgModule({
  imports: [     
    BrowserModule,
    AppRoutingModule
  ],
  declarations: [
    AppComponent,
    AddressComponent,
    PageNotFoundComponent
  ],
  providers: [ ],
  bootstrap: [ AppComponent ]
})
export class AppModule { 
  constructor() {
     console.log('AppModule loaded.');
  }
} 
Enter fullscreen mode Exit fullscreen mode

We will not import feature module in imports metadata of @NgModule decorator, so that it could not load eagerly.

When we access the application first time, AppModule will be loaded eagerly. We will get log in browser console as following.

AppModule loaded.
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
Enter fullscreen mode Exit fullscreen mode

When we click on country, then CountryModule will be loaded lazily. Find the log.

CountryModule loaded.
Enter fullscreen mode Exit fullscreen mode

When we click on person, then PersonModule will be loaded lazily. Find the log.

PersonModule loaded.
Enter fullscreen mode Exit fullscreen mode

Checkout to main blog Angular Module Loading strategies

Top comments (0)