In this article, we are going to discuss feature modules in Angular and lazy load them with the help of one practical example.
Agenda
- What is Angular?
- What is a Module?
- Feature Module in Angular
- Benefits of Feature Module
- Lazy Loading
- Feature Module Example
Prerequisites
- Angular CLI
- Node JS
- VS Code Editor
What is Angular?
Angular is a popular open-source JavaScript framework for building web applications. It was developed by Google and is currently maintained by the Angular Team at Google. Angular allows developers to create dynamic, single-page applications (SPAs) and provides a structured approach to building complex web applications.
What is a Module?
In programming, a module is a self-contained unit of code that performs a specific task or provides a set of related functions. It is a way of organizing and managing code in a modular and reusable manner.
A module can be a separate file or a collection of files that contain functions, classes, variables, or other code components. It encapsulates a specific set of functionalities, making it easier to understand, test, and maintain code.
Feature Module in Angular
In Angular, a feature module is a way to organize and encapsulate a specific set of features and functionality within an application.
It contains a group of related components, directives, services, and a few other files. It helps us maintain and manage the application codebase.
For example, Suppose we have an online shopping application that contains feature modules like user registration, products, cart, and many more with its services, directives, components, and routing-related configuration.
Benefits of Feature Module
Here are some key benefits of feature modules in Angular:
- Encapsulation: Feature modules encapsulate related components, directives, services, and other code files within a specific feature or functionality. This encapsulation provides a clear boundary and separation of concerns, making it easier to understand and maintain code.
- Code Organization: Feature modules help organize your codebase by grouping related code files together. This organization enhances code readability and allows developers to navigate the codebase more efficiently.
- Code Reusability: Feature modules can be reused across multiple applications or within the same application. This reusability promotes modular and scalable development by allowing you to extract and reuse modules with specific functionalities.
- Lazy Loading: The lazy loading feature allows you to load feature modules on-demand, improving the initial load time and performance of your application. Lazy loading ensures that only the necessary modules are loaded when navigating to specific routes, reducing the initial bundle size and optimizing the user experience.
- Dependency Management: Feature modules in Angular have their own set of dependencies and can manage their own imports and exports. This helps in managing dependencies and prevents naming conflicts with other modules in your application.
- Clear Interfaces: Feature modules define clear interfaces through exports, providing a way to communicate with other parts of the application. By exporting specific components, directives, or services, other modules can make use of them and interact with the features provided by the module.
- Testing and Debugging: Feature modules enhance testability and debugging capabilities. By encapsulating related code files, it becomes easier to write unit tests specific to a module’s functionalities and isolate any issues or bugs within that module.
Lazy Loading
Lazy loading is a technique in Angular that allows you to load modules asynchronously and on-demand when they are needed. It is a powerful feature that helps improve the initial loading time of your application by loading only the necessary code for the current route instead of loading the entire application upfront.
Feature Module Example
Step 1. Install NodeJS: https://nodejs.org/en/download
Step 2. Install Angular CLI using the following command:
npm install -g @angular/cli
Step 3. Verify NodeJS and Angular CLI are installed or not using the following commands:
node –version
ng version
Step 4. Create a new Angular Application.
ng new angular-modules-demo
Step 5. Open the Angular application in one of the editors, like VS Code, and install the bootstrap with the help of the following command:
npm install bootstrap
next, add the bootstrap script inside the angular.json file inside the scripts and styles section
"styles": [
"src/styles.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"./node_modules/bootstrap/dist/js/bootstrap.min.js"
]
Step 6. Create the “FirstModule” feature module.
Navigate into the project directory:
cd angular-modules-demo
Next, create the “FirstModule” feature module by running the following command:
ng generate module modules/first-module –routing
This will generate a new module named FirstModule under the modules directory, along with a routing module named first-module-routing.module.ts specific to this module.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FirstModuleRoutingModule } from './first-module-routing.module';
import { FirstModuleComponent } from './first-module.component';
@NgModule({
declarations: [
FirstModuleComponent
],
imports: [
CommonModule,
FirstModuleRoutingModule
]
})
export class FirstModuleModule { }
Step 7. Create the default component for FirstModule.
Generate the default component for “FirstModule” by running the following command:
ng generate component modules/first-module/first-module-component
This will create a new component named FirstModuletComponent within the first module.
import { Component } from '@angular/core';
@Component({
selector: 'app-first-module',
templateUrl: './first-module.component.html',
styleUrls: ['./first-module.component.css']
})
export class FirstModuleComponent {
}
Step 8. Configure the routing for FirstModule.
Open the first-module-routing.module.ts file under the modules/first-module directory and modify it as follows:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FirstModuleComponent } from './first-module.component';
const routes: Routes = [{ path: '', component: FirstModuleComponent }];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FirstModuleRoutingModule { }
Step 9. Create the “SecondModule” feature module
Create the “SecondModule” feature module by running the following command:
ng generate module modules/second-module –routing
This will generate a new module named SecondModule under the modules directory, along with a routing module named second-module-routing.module.ts specific to this module.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SecondModuleRoutingModule } from './second-module-routing.module';
import { SecondModuleComponent } from './second-module.component';
@NgModule({
declarations: [
SecondModuleComponent
],
imports: [
CommonModule,
SecondModuleRoutingModule
]
})
export class SecondModuleModule { }
Step 10. Create the default component for SecondModule.
Generate the default component for “SecondModule” by running the following command:
ng generate component modules/second-module/second-module-component
This will create a new component named SecondModuleComponent within the second module.
import { Component } from '@angular/core';
@Component({
selector: 'app-second-module',
templateUrl: './second-module.component.html',
styleUrls: ['./second-module.component.css']
})
export class SecondModuleComponent {
}
Step 11. Configure the routing for the second module.
Open the second-module-routing.module.ts file under the modules/second-module directory and modify it as follows:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SecondModuleComponent } from './second-module.component';
const routes: Routes = [{ path: '', component: SecondModuleComponent }];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class SecondModuleRoutingModule { }
Step 12. Update the App Routing
Open the app-routing.module.ts file under the src/app directory and modify it as follows:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'first-module', loadChildren: () => import('./modules/first-module/first-module.module').then(m => m.FirstModuleModule) },
{ path: 'second-module', loadChildren: () => import('./modules/second-module/second-module.module').then(m => m.SecondModuleModule) },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Here we use lazy loading in this example to navigate features modules based on navigations.
To implement lazy loading in Angular, follow these steps:
Open the main app routing module, app-routing.module.ts, and update the routes to use the loadChildren property instead of the component property for the routes that you want to lazy load. For example:
const routes: Routes = [
{ path: 'first-module', loadChildren: () => import('./modules/first-module/first-module.module').then(m => m.FirstModuleModule) },
{ path: 'second-module', loadChildren: () => import('./modules/second-module/second-module.module').then(m => m.SecondModuleModule) },
];
By using lazy loading, you can split your application into smaller, more manageable chunks, improving performance by loading modules only when they are required. This approach is particularly useful for larger applications or when you have sections of your application that are accessed less frequently.
Lazy-loaded modules are loaded asynchronously and cached by the Angular router, so subsequent visits to the same route will load the module from the cache instead of making a new request to the server.
Step 13. Update the app.component.html file.
<button type="button" class="btn btn-primary" routerLink="first-module">First Module</button>
<button type="button" class="btn btn-secondary" routerLink="second-module">Second Module</button>
<router-outlet></router-outlet>
Here we used bootstrap buttons with a router link for navigation purposes and, at the bottom, a router outlet to render different components of the feature module based on navigation.
Step 14. Finally, start the development server by running the following command:
ng serve
Navigate to http://localhost:4200 in your web browser, and you should see the Angular Modules Demo App with two navigation links: “First Module” and “Second Module.” Clicking on each link will lazily load and display the corresponding module’s component.
When we navigate the feature module, only its corresponding files will get loaded because we are lazy to load them with load children, as shown in the above image under the application console. Also, it improves performance when we have a big project with different complex modules.
GitHub: https://github.com/Jaydeep-007/angular-modules-demo
Conclusion
In this article, we discussed the feature module, its benefits, and one practical example with step-by-step implementation.
Happy Coding!