Author avatar

Parul Saxena

Feature Modules in Angular: Breaking Down a Large App

Parul Saxena

  • Jul 2, 2020
  • 9 Min read
  • 481 Views
  • Jul 2, 2020
  • 9 Min read
  • 481 Views
Languages Frameworks and Tools
Front End Web Developer
Client-side Frameworks
Angular

Introduction

When you create a new Angular project using Angular CLI command, you get a fresh app along with a module called AppModule. You can very well code the entire app in this module itself, but that won't be a good idea because it will make the loading of the app very slow depending on how big the app is. You must break a large app into feature modules so that you can:

  1. Avoid loading the entire app at once
  2. Pre-load feature modules in the background
  3. Lazy load feature modules on demand when a user accesses a functionality implemented inside a feature module

In this guide, you will learn about the advantages of feature modules and lazy loading of a feature module, and understand the difference it makes for an app's load time.

Advantages of Feature Modules

  • Lazy Loading - One of the advantages of breaking the app into multiple feature modules is the ability to load code lazily on-demand. When a user hits an Angular app hosted on a web server, the browser downloads all necessary files for the app to run successfully. If the app is partitioned into multiple feature modules but if all of them are eagerly loaded, then all the feature modules are also downloaded, which increases the app's load time. But if some of the feature modules are lazily loaded, then the code for them is not downloaded on the app's first run. Code for lazily loaded feature modules is downloaded only when a user tries to access a functionality that is a part of a lazily loaded feature module.

  • Clean Code - Breaking the app into multiple feature modules makes the code clean, as all the artifacts of a particular module are grouped inside the folder of that module.

  • Locate code faster - Since all the artifacts of a particular module are grouped inside the folder of that module, it becomes fast and easy to locate the code.

Getting Started

Prerequisites

To complete this guide, you should have:

  1. Node - 12.17.0
  2. Angular CLI - 9.0.2
  3. Visual Studio Code - 1.45.1

Create an Angular Project

  1. Execute the following command to create an Angular project.

ng new feature-modules-demo

  1. When prompted to add routing to the app, press Y.
  2. When prompted to choose stylesheet format, press ENTER.

Opening the Generated App in Visual Studio Code

  1. Click on the File menu in the top menu bar and select the menu option Open Folder.
  2. In the file dialog box, navigate to the folder where you generated the app.
  3. In this folder, you should see a folder named feature-modules-demo. Select this folder and click Open in the file dialog box.

Setting up the Project

You will install Twitter Bootstrap and jQuery and reference them in your project so that you can use some of the form styles to make the form look good.

  1. Go to command prompt and run following command:

cd feature-modules-demo

  1. Run the following command to install jQuery:

npm i jquery

  1. Run the following command to install Bootstrap:

npm i bootstrap

  1. In Visual Studio Code, open the file angular.json.
  2. Add the following line in the styles array before src/style.css.

"node_modules/bootstrap/dist/css/bootstrap.min.css",

  1. Add following lines in the scripts array:

"node_modules/jquery/dist/jquery.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js"

  1. In Visual Studio Code, open the file src > index.html.
  2. At line number 10, in the body element, add the following class:

class="container"

The final code should look like:

1
2
3
<body class="container">
  <app-root></app-root>
</body>

Now the project is all set for development.

Creating a User Profile Feature Module

Run the following command to generate a user profile module:

ng generate module user-profile

Creating a Login Component in User Profile Module

  1. Run the following command to generate login component in user profile module:

ng generate component --module user-profile login

  1. In Visual Studio Code, open the file src > app > login > login.component.html, delete the contents of the file and add following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<h1>Login</h1>
<hr>
<div class="col-md-4">
  <form autocomplete="off">
    <div class="form-group" >
      <label for="userName">User Name:</label>
      <input id="userName" type="text" class="form-control" placeholder="User Name..." />
    </div>
    <div class="form-group" >
      <label for="password">Password:</label>
      <input id="password" type="password" class="form-control"placeholder="Password..." />
    </div>
        
    <button type="submit" class="btn btn-primary">Login</button>
    <button type="button" class="btn btn-default">Cancel</button>
  </form>
</div>

Adding Routes to the User Profile Module

In Visual Studio Code, open the file src > app > user-profile > user-profile.module.ts, delete the contents of the file, and add following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoginComponent } from '../login/login.component';
import { Routes, RouterModule } from '@angular/router';

const routes:Routes = [
  {path: 'login', component: LoginComponent}
];

@NgModule({
  declarations: [LoginComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ]
})
export class UserProfileModule { }

Lazy Loading a User Profile Module

In Visual Studio Code, open the file src > app > app-routing.module.ts, delete the contents of the file and add following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


const routes: Routes = [
  {path:'user', loadChildren: () => import(`./user-profile/user-profile.module`).then(m => m.UserProfileModule)}
];

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

Adding Link to Lazily Loaded Module

In Visual Studio Code, open the file src > app > app.component.html, delete the contents of the file and add following code:

1
2
3
4
5
6
7
8
9
10
<div class="row">
	<div class="col-md-2">
		<a [routerLink]="['user/login']">Login</a>
	</div>
</div>
<div class="row">
	<div class="col-md-12">
		<router-outlet></router-outlet>
	</div>
</div>

Checking the Lazily Loaded Module

In this section, you will notice the advantages of the lazily loaded user profile feature module.

  1. Run the following command in the command prompt to start Angular Development Server in watch mode: ng serve
  2. If prompted to share Angular CLI usage data, press the N key to not share it.
  3. Open a browser and type the following URL in the address bar to launch the app: http://localhost:4200.
  4. Open the developer toolbar in the browser that you have used to browse the app. If you are using Chrome, press CTRL+SHIFT+J and the developer toolbar will open for you.
  5. In the developer tool bar, click on the sources tab, and notice all the files that are listed. Notice that there is no file with the name user-profile-user-profile-module.js.
  6. Click the Login link and notice that the file user-profile-user-profile-module.js is downloaded immediately.

This is the advantage of lazily loaded feature modules where the code is not loaded in memory until needed.

Pre-loading a Lazily Loaded Feature Module

In Visual Studio Code, open file src > app > app-routing.module.ts, delete the contents of the file, and add following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { NgModule } from '@angular/core';
import { Routes, RouterModule, PreloadAllModules } from '@angular/router';


const routes: Routes = [
  {path:'user', loadChildren: () => import(`./user-profile/user-profile.module`).then(m => m.UserProfileModule)}
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {
		// Tell the router to use the HashLocationStrategy.
		useHash: true,
		enableTracing: false,
 
		// This will tell Angular to preload the lazy-loaded routes after the
		// application has been bootstrapped. This will extend to both top-level
		// and nested lazy-loaded modules.
		preloadingStrategy: PreloadAllModules
	})],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Checking the Pre-loading of a Lazily Loaded Module

  1. Hit the following URL in browser: http://localhost:4200
  2. Notice the file list in the sources tab. The file user-profile-user-profile-module.js gets loaded automatically without clicking the Login link.

This is the second advantage of lazily loaded feature modules. The feature modules were loaded in the background, after the first rendering of the app was complete.

Conclusion

In this guide, you have learned:

  1. The advantages of feature modules
  2. Lazy loading of feature modules
  3. Pre-loading lazily loaded feature modules

For more information, follow the Lazy loading ngmodules guide.

5