DEV Community

Krishna Bhamare
Krishna Bhamare

Posted on

2 2

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

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay