Angular Feature Module And Lazy Loading - One Of Way To Increase Application Performance

Introduction 

 
Today, in this article, we will discuss the most significant features of Angular Framework i.e. Feature Modules. With the help of Angular Framework, we can develop both large-scale based application or small scale based application. Actually, with the help of Angular Modules, we can be designed our application into a part of different modules so that we can manage the application in a much better way. Since, if we use one single block or module for our application, then when the application starts growing to incorporate the new features and functionalities, it becomes a tedious job to manage the entire mode under a single block or module. In the same place, if we use multiple modules or blocks, then the maintenance of the code is easier. In this way, we can incorporate the new functionality or features in a new module and then include that module in our application.
 
So, there are many possible ways to group the functionalities into modules and the decision always depends upon the developers to find the best way for the application. So, when we break the application into multiple modules, then it becomes one of the important responsibilities of developers to maintains all modules so that performance of the application can be boosted up. We can break the application into multiple modules and then import all modules references into the bootstrapped module. The result of this approach will be that application loading will be slow as the application size increases. So, the best approach is that break the application into multiple modules as a Feature Module which can provide the following benefits:
  1. It will avoid the loading of the entire application at a time.
  2. Can be pre-loaded the features modules in the background
  3. Lazy load of the feature modules on demand means when the user wants to access that module or related functionality then only that particular module will be loaded into the DOM.
So, in this article, we will discuss the concept of Feature Modules and the Lazy loading of a Feature Module and also demonstrate how to implement this concept into any Angular Application.
 

What are Feature Modules in Angular?

 
So, in Angular Framework, a Feature Module is simply an Angular module with module related kinds of stuff and purpose. But the main difference is that is not the root module of the application. Feature module is just an additional typescript based class with the @NgModule decorator and registered metadata. Feature modules isolate the applications based on the functionality or business operation and it collaborates with the root modules or any other feature modules. The main purpose of the feature modules is to break down the functionality which focuses on any particular internal business operation or functionality that needs to be dedicated as a module so that we can achieve modularity in the application. With the help of feature modules, we also can restrict the responsibility of the root modules and help the root module to keep it thin and small.
 
Feature Module And Lazy Loading - One Of Way To Increase Application Performance
 
In general, we can define five different types of feature modules in an application – Domain, Routed, Routing, Service, and Widget. Each of these types of feature module concentrates and provides specific types of utilities.
  • Domain Feature Modules – This type of feature module is based on the application navigation like Product or Product feature modules.
  • Routed Feature Modules – All the lazy loaded modules are known as routed modules.
  • Routing Feature Modules – This type of feature module is based on the routing and its related functionality based like Route Guards.
  • Service Feature Modules – The service feature module mainly acts as a utility module related to the API request-response. This feature is mainly imported in the root module. It is mostly used for the data messaging API request-response.
  • Widget Feature Modules – This feature module is based on the Widget related modules which may contain utility, pipes, directive, etc.
Every feature module always has the following functionalities:
  • We can declare a separate set of Components, Directives, and Pipes for the feature modules.
  • We can also export the feature module just like another angular module so that other angular modules can consume its component, directives, and pipes.
  • Feature modules can provide services to itself and other modules also.
  • The feature module can import other angular modules into its module and use its components, directives, and pipes.

Benefits of Feature Modules

 
Now, in the above section, we discuss the concept of Feature module in any Angular application. So, before going to implement or demonstrate the feature module, we first need to understand what the benefits of feature module implementations are:
  • The feature module always helps us to define clear separation for the features.
  • With the help of the feature module, we can organize the code and structure in a much better way. It will always help us to decouple the non-related functionality and features.
  • In the case of a feature module, the module can be used lazy loaded modules. Lazy loaded modules will help in creating scalable applications.
  • The feature module always follows the SOC (Separation of Concern) principle. It helps us to separate the feature and code responsibility.
  • With the help of Lazy-loading functionality, the initial load time of the application can be reduced. Angular has preload features that load the module still not loading it completely.
  • Practically we can do everything with the root module, say app module in our case. Putting everything in the root module pollutes the root module. Feature module provides a set of functionality, flow, and forms focused on application needs.

What is Lazy Loading of Modules?

 
The lazy loading technique is not a new one introduced by the Angular Framework. It is a process or method to download the data on-demand, say, for example, Documents, JavaScript files, CSS, Images, and Videos in small pieces. This process or method normally performs the data loads operations in chunks instead of bigger pieces to improve the performance of the application.
 
Normally, we already included all the feature modules within the root module with the help of the import statement. So, when the application starts, all the files related to the modules defined or imported within the root modules will be downloaded first and then the application loading will be completed. If that file size is large, then application initial loading will take time since it will be complete only when the downloading part is complete. This type of loading is normally known as eager loading.
 
The standard import syntax in eager loading is always static. That’s why it always evaluated all code at the load time. In this circumstance, if we want to load a particular module conditionally or on-demand, then we need to use the dynamic import instead of static import. This dynamic import concept is normally known as the Lazy loading of angular modules. With the help of Lazy loading, we can shrink the size of the application as only required modules will be loaded by the browser at the startup. The rest of the modules will be downloaded and loaded dynamically on-demand concept.
 

Benefits of Lazy Loading Modules

 
So, as per the Angular Framework, if we are using the eager loading technique, then if the application consists of many or a large number of components, it will take a long time to load all components when an app is a download. Due to this, the user experience related to the application will be degraded. So, if we consider that first impressions are the last impressions in case of any application, then it will be a very serious issue. So, to overcome this limitation of eager loading, Angular Framework has introduced the Lazy Loading strategy. In this process, it loads only those components which are required to render the page. So, it saves time and renders the application much faster than the eager loading. Lazy loading also has many benefits, such as:
  • It loads only those components which are required to render within the page.
  • It loads the application much faster compared to the eager loading.
  • It helps us to improve the user experience.

Steps to Perform Feature Module with Lazy Loading in Angular Applications

 
Now, it's time to demonstrate how we can implement Feature Modules with Lazy Loading in any angular application. For that purpose, we are going to develop one application which contains the Top 10 Player details for different sports. The final output of the application is just like below:
 
Feature Module And Lazy Loading - One Of Way To Increase Application Performance
 
For that purpose, first, we create an Angular Project with the help of Angular CLI as per the below folder structure:
 
Feature Module And Lazy Loading - One Of Way To Increase Application Performance
 
Now, we add the below code in the files, as shown in the above structure:
 
app.component.css
  1. h1 {  
  2.     font-size3em;  
  3.     color#999;  
  4.     margin-bottom0;  
  5. }  
  6.   
  7. h2 {  
  8.     font-size2em;  
  9.     margin-top0;  
  10.     padding-top0;  
  11.     color:crimson;  
  12. }  
  13.   
  14. nav a {  
  15.     padding5px 10px;  
  16.     text-decorationnone;  
  17.     margin-top10px;  
  18.     display: inline-block;  
  19.     background-color#eee;  
  20.     border-radius: 4px;  
  21. }  
  22.   
  23. nav a:visited, a:link {  
  24.     color#607D8B;  
  25. }  
  26.   
  27. nav a:hover {  
  28.     color#039be5;  
  29.     background-color#CFD8DC;  
  30. }  
  31.   
  32. nav a.active {  
  33.     color#039be5;  
  34. }  
app.component.ts
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'Angular Feature Module Demo';  
  10. }  
app.component.html
  1. <h1>{{title}}</h1>  
  2. <nav>  
  3.     <a routerLink="/home" routerLinkActive="active">Home</a>  
  4.     <a routerLinkActive="active">Cricket</a>  
  5.     <a routerLinkActive="active">Football</a>  
  6.     <a routerLinkActive="active">Tenis</a>  
  7. </nav>  
  8. <br>  
  9. <router-outlet></router-outlet>  
home.component.ts
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'home-page',  
  5.   template: `  
  6.     <div>  
  7.         <h2>Demonstration of Feature Modules with Lazy Loading Concept</h2>  
  8.     </div>  
  9.   `,  
  10.   styleUrls: ['./app.component.css']  
  11. })  
  12. export class HomeComponent {  
  13.     
  14. }  
app.module.ts
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { AppComponent } from './app.component';  
  6. import { HomeComponent } from './home.component';  
  7.   
  8. @NgModule({  
  9.   declarations: [  
  10.     AppComponent, HomeComponent  
  11.   ],  
  12.   imports: [  
  13.     BrowserModule,  
  14.     AppRoutingModule  
  15.   ],  
  16.   providers: [],  
  17.   bootstrap: [AppComponent]  
  18. })  
  19. export class AppModule { }  
app-routing.module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { HomeComponent } from './home.component';  
  4.   
  5. const routes: Routes = [  
  6.     { path: '', redirectTo: 'home', pathMatch: 'full' },  
  7.     { path: 'home', component: HomeComponent },  
  8.      
  9. ];  
  10.   
  11. @NgModule({  
  12.   imports: [RouterModule.forRoot(routes)],  
  13.   exports: [RouterModule]  
  14. })  
  15. export class AppRoutingModule { }  
Now, execute the program and check the output in the browser:
Feature Module And Lazy Loading - One Of Way To Increase Application Performance
 
So, we have already defined the root module in the application. Now, it's time to define the feature module. First, we will define one feature module called FootballModule which mainly contains the information related to football. So, for that purpose, we create a folder called football under the app folder and add the below files. We define another angular module which contains all the related files required to define a module.
 
Feature Module And Lazy Loading - One Of Way To Increase Application Performance
 
football.component.css
  1. [class*='col-'] {  
  2.     floatleft;  
  3.     padding-right20px;  
  4.     padding-bottom20px;  
  5. }  
  6.   
  7. [class*='col-']:last-of-type {  
  8.     padding-right0;  
  9. }  
  10.   
  11. a {  
  12.     text-decorationnone;  
  13. }  
  14.   
  15. *, *:after, *:before {  
  16.     -webkit-box-sizing: border-box;  
  17.     -moz-box-sizing: border-box;  
  18.     box-sizing: border-box;  
  19. }  
  20.   
  21. h3 {  
  22.     text-aligncenter;  
  23.     margin-bottom0;  
  24. }  
  25.   
  26. h4 {  
  27.     positionrelative;  
  28. }  
  29.   
  30. .grid {  
  31.     margin0;  
  32. }  
  33.   
  34. .col-1-4 {  
  35.     width25%;  
  36. }  
  37.   
  38. .module {  
  39.     padding20px;  
  40.     text-aligncenter;  
  41.     colorrgb(1411);  
  42.     max-height120px;  
  43.     min-width120px;  
  44.     background-color#7ef7a6;  
  45.     border-radius: 2px;  
  46. }  
  47.   
  48. .module:hover {  
  49.     background-color#EEE;  
  50.     cursorpointer;  
  51.     color#607d8b;  
  52. }  
  53.   
  54. .grid-pad {  
  55.     padding10px 0;  
  56. }  
  57.   
  58. .grid-pad > [class*='col-']:last-of-type {  
  59.     padding-right20px;  
  60. }  
  61.   
  62. @media (max-width600px) {  
  63.     .module {  
  64.         font-size10px;  
  65.         max-height75px;  
  66.     }  
  67. }  
  68.   
  69. @media (max-width1024px) {  
  70.     .grid {  
  71.         margin0;  
  72.     }  
  73.   
  74.     .module {  
  75.         min-width60px;  
  76.     }  
  77. }  
football.component.html
  1. <h2>  
  2.     <a href="https://www.ea.com/games/fifa/fifa-20/ratings/fifa-20-player-ratings-top-100">  
  3.         Football - Top 10 Player (FIFA Ranking)  
  4.     </a>  
  5. </h2>  
  6. <div class="grid grid-pad">  
  7.     <a *ngFor="let data of footballData" class="col-1-4">  
  8.         <div class="module hero">  
  9.             <h4>{{data.name}}</h4>  
  10.         </div>  
  11.     </a>  
  12. </div>  
football.component.ts
  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'football-info',  
  5.   templateUrl: './football.component.html',  
  6.   styleUrls: ['./football.component.css']  
  7. })  
  8. export class FootballInfoComponent implements OnInit {  
  9.   public footballData:Array<any>=[];  
  10.   
  11.   constructor() {  
  12.       
  13.   }  
  14.   
  15.   ngOnInit(): void {  
  16.     this.footballData = [  
  17.         { id: 1, name: 'Lionel Messi' },  
  18.         { id: 2, name: 'Cristiano Ronaldo' },  
  19.         { id: 3, name: 'Neymar Jr.' },  
  20.         { id: 4, name: 'Eden Hazard' },  
  21.         { id: 5, name: 'Kevin De Bruyne' },  
  22.         { id: 6, name: 'Jan Oblak' },  
  23.         { id: 7, name: 'Virgil Van Dijk' },  
  24.         { id: 8, name: 'Mohamed Salah' },  
  25.         { id: 9, name: 'Luka Modrić' },  
  26.         { id: 10, name: 'Marc-André ter Stegen' }  
  27.       ];  
  28.   }  
  29. }  
football.home.component.ts
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'football-home',  
  5.     template: '<router-outlet></router-outlet>'  
  6. })  
  7. export class FootballHomeComponent {  
  8.       
  9.     constructor() {  
  10.     }  
  11. }  
football.module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { CommonModule } from '@angular/common';  
  3. import { FormsModule, ReactiveFormsModule } from "@angular/forms";  
  4.   
  5. import { FootballRoutingModule } from './football.routing.module';  
  6. import { FootballHomeComponent } from './football.home.component';  
  7. import { FootballInfoComponent } from './football.component';  
  8.   
  9. @NgModule({  
  10.   imports: [  
  11.     CommonModule,FormsModule, ReactiveFormsModule,   
  12.     FootballRoutingModule  
  13.   ],  
  14.   declarations: [  
  15.     FootballHomeComponent, FootballInfoComponent  
  16.   ],  
  17.   entryComponents:[  
  18.     FootballInfoComponent  
  19.   ],  
  20.   bootstrap:[FootballHomeComponent]  
  21. })  
  22. export class FootballModule {  
  23.   
  24. }  
football.routing.module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { RouterModule, Routes } from '@angular/router';  
  3.   
  4. import { FootballHomeComponent } from './football.home.component';  
  5. import { FootballInfoComponent } from './football.component';  
  6.   
  7. const routes: Routes = [  
  8.     {   
  9.       path: '',   
  10.       component: FootballHomeComponent,  
  11.       children: [  
  12.         { path: 'top10fifa', component: FootballInfoComponent},  
  13.     ]  
  14.     }  
  15. ];  
  16.   
  17. @NgModule({  
  18.   imports: [  
  19.     RouterModule.forChild(routes)  
  20.   ],  
  21.   exports: [  
  22.     RouterModule  
  23.   ]  
  24. })  
  25. export class FootballRoutingModule {  
  26. }  
Now, we define the Football feature module. After it, in the root routes we need to use loadChildren to introduce the lazy loading with the help of the import function.
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { HomeComponent } from './home.component';  
  4.   
  5. const routes: Routes = [  
  6.     { path: '', redirectTo: 'home', pathMatch: 'full' },  
  7.     { path: 'home', component: HomeComponent },     
  8.     {   
  9.       path: 'football',   
  10.       loadChildren: () => import('./football/football.module').then(module => module.FootballModule)  
  11.     }  
  12. ];  
  13.   
  14. @NgModule({  
  15.   imports: [RouterModule.forRoot(routes)],  
  16.   exports: [RouterModule]  
  17. })  
  18. export class AppRoutingModule { }  
LoadChildren is a method that will be executed only when we need to access that particular route. Only at that time, this particular module will be loaded into the DOM. For that we will provide the related routerlink against the link text:
  1. <h1>{{title}}</h1>  
  2. <nav>  
  3.     <a routerLink="/home" routerLinkActive="active">Home</a>  
  4.     <a routerLinkActive="active">Cricket</a>  
  5.     <a routerLink="/football/top10fifa" routerLinkActive="active">Football</a>  
  6.     <a routerLinkActive="active">Tenis</a>  
  7. </nav>  
  8. <br>  
  9. <router-outlet></router-outlet>  
Now, check the output in the browser:
Feature Module And Lazy Loading - One Of Way To Increase Application Performance
 
If we inspect the application with the browser’s Network tab, we will see that when we click on the football link then only football module related js file is download in the browser. If the files are download once, then it will not download again until we close the browser or reload the main application.
 
Similarly, we can create Cricket and tennis football with the same types of functionality and then include them in the app routing module as child modules. Also, the Angular framework provides another technique called Preloading Strategy for the Lazy loading module concept. In this process, app routes first load the route related component to render the page as quickly as possible. After the first route loading complete, it starts loading the other modules as a background process. In this way, other modules will be ready automatically, and the user does not need to wait for a load of all the components of that module. To implement the preloading strategy, we just need to include that into the root route module as below,
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule, PreloadingStrategy, PreloadAllModules } from '@angular/router';  
  3. import { HomeComponent } from './home.component';  
  4.   
  5. const routes: Routes = [  
  6.     { path: '', redirectTo: 'home', pathMatch: 'full' },  
  7.     { path: 'home', component: HomeComponent },  
  8.     {   
  9.       path: 'cricket',   
  10.       loadChildren: () => import('./cricket/cricket.module').then(module => module.CricketModule)  
  11.     },  
  12.     {   
  13.       path: 'football',   
  14.       loadChildren: () => import('./football/football.module').then(module => module.FootballModule)  
  15.     },  
  16.     {   
  17.       path: 'tenis',   
  18.       loadChildren: () => import('./tennis/tennis.module').then(module => module.TennisModule)  
  19.     },  
  20. ];  
  21.   
  22. @NgModule({  
  23.   imports: [RouterModule.forRoot(routes, {  
  24.     preloadingStrategy : PreloadAllModules  
  25.   })],  
  26.   exports: [RouterModule]  
  27. })  
  28. export class AppRoutingModule { }  
So, now when we check the application loading in the browser tab, we will see that when the application load at the time feature module related files already downloaded.
 
Feature Module And Lazy Loading - One Of Way To Increase Application Performance
 

Conclusion

 
So, Feature Module and Lazy Loading are some of the essential features in any application. When we use these in any application, it affects many other things like user experience, performance, bootstrapping an application, etc. With the help of some extra configuration setting, it will provide us a lot of benefits in any application. I hope, this article will help you to understand the basic concept of feature modules and lazy loading. Also, help you to implement these functionalities in an Angular Application. Any feedback or query related to this article is most welcome.