Learnitweb

Introduction to Angular modules and NgModule

1. Introduction

In this tutorial, we’ll discuss modules and NgModules in Angular. Angular applications are modular. If you create a simple Angular application using Angular CLI, you’ll observe that it has AppModule. Angular modules enables several important features like ahead of time compilation and lazy loading.

A module in Angular is a container for a cohesive and inter-related set of code. A module can contain code related to particular workflow or functionality of application. For example, if your application has two main workflows, one for admin and one for general user, then your application code can have two modules – admin module and user module. All code files related to a particular module like components, service providers, pipes, directives etc. can be put together logically in one module.

A module can import functionality from other module and similarly export functionality to be used by other module. An Angular module helps in splitting up an application into smaller parts. This modular architecture allows you to create libraries of components which can be easily shared and used by other application. Modular nature of application allows you to lazy load each module separately and thus enhancing speed of application.

Modules can be loaded eagerly when the application starts or lazy loaded asynchronously by the router.

Every Angular application has at least one module which is called as root module. The root module is named as AppModule which resides in app.module.ts. This root module is used to bootstrap the application.

2. What we’ll learn in this tutorial?

In this tutorial, we’ll do the following:

  1. Create a feature module.
  2. Create a component and add it to the feature module.
  3. Import a feature module in another module (root module for our example).
  4. Use component in feature module in another module.

Assumption for this tutorial: We assume that you know how to create a simple Angular application. You should be able to create and run it in browser. You can create a new application in CLI using ng new module-example.

3. Examples of module in Angular

Following are few examples of Angular modules:

  • CommonModuleCommonModule has all the basic Angular directives and pipes, such as NgIf, NgForOf, DecimalPipe and so on.
  • FormsModuleFormsModule has the required providers and directives for template-driven forms.
  • ReactiveFormsModuleReactiveFormsModule has the required providers and directives for reactive forms.

4. Benefits of modular application in Angular

  • Module acts as a container for inter-related code. This result in better organized code logically.
  • Module allows to create libraries which can be exported to be used by other applications.
  • Module enables various important features like ahead of time compilation and lazy loading.

5. Code and metadata inside a module

Once you create a new application, it has a root module which has a name AppModule. This root module is in file app.module.ts and following is its code:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

You should note the following points by looking at code:

  • The @NgModule decorator that marks the class as NgModule.
  • You can mention components, directives and pipes that are part of the module in the declarations array.
  • You can mention other modules to be imported to be in imports array.
  • You can mention the services that are part of this module in providers array.
  • You can mentioned the root component that Angular creates and inserts into the index.html host web page in the bootstrap option. This option is usually found in root module but not in child modules.

A root NgModule does not need to export anything because other modules don’t need to import the root NgModule.

6. Why do we need module?

As mentioned in Angular documentation: NgModules provide a compilation context for their components. A template defines a view. A view can embed other views. This creates a view hierarchy. All the information related to view is retrieved from the module. These required components can be in the same module or different module.

7. Comparison of NgModules and JavaScript modules

The Angular framework itself is loaded as a set of JavaScript modules but it is different from JavaScript module. Following are the differences:

  • An NgModule is a class marked by the @NgModule decorator whereas in case of JavaScript module it is not required.
  • A JavaScript module is an individual file with JavaScript code whereas in case of NgModule there is no standalone file.
  • An NgModule has metadata like declarations, imports, providers and so on. Whereas the JavaScript module has no such metadata.

8. What is a Feature Module?

A feature module as the name suggests contains code for a particular feature of an application. A feature module can contain all building blocks like components, directive, services and pipe.

It is organizational best practice to create a separate feature module to keep inter-related code for a particular feature of your application.

We’ll now create a feature module, add a component to this feature module and will use it in another module (root module for our example).

8.1. Create a feature module

The command to generate a feature module is:

ng generate module <modulename>

Example:

ng generate module Admin

You can omit the “Module” suffix from the module name as CLI will append it.

8.2 Add a component in feature module

To add a component, we have to first create a component. Run the following command to create the component.

ng generate component admin/adminDashboard

Here admin is the name of the directory in which AdminDashboardComponent component will be added. The template file of the components contains a simple message:

<p>admin-dashboard works!</p>

To add the component in the AdminModule, add AdminDashboardComponent in the declarations array of AdminModule.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';

@NgModule({
  declarations: [AdminDashboardComponent],
  imports: [CommonModule],
})
export class AdminModule {}

8.3 Import a feature module in another module

To import a feature module in another module (AppModule in our case), add the module in the imports array of the module. We have added AdminModule in the imports array of AppModule.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AdminModule } from './admin/admin.module';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, AdminModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

8.4 Exporting a component from a module

We have added AdminDashboardComponent to the AdminModule. We also included AdminModule in the AppModule but we still can’t access AdminDashboardComponent in AppModule. The reason is AdminModule does not export AdminDashboardComponent.

To export or share a component from a module, add the component in the exports array of the module.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';

@NgModule({
  declarations: [AdminDashboardComponent],
  imports: [CommonModule],
  exports: [AdminDashboardComponent],
})
export class AdminModule {}  

8.5 Final steps before executing application

Include app-admin-dashboard selector for AdminDashboardComponent in app.component.html. In the end, run the application.

You’ll see the message “admin-dashboard works!” in the browser window at the place where you place <app-admin-dashboard></app-admin-dashboard>.

9. Angular modules and visibility

There is one important you should notice from this example – adding AdminDashboardComponent to the declarations of AdminModule does not automatically make the component visible to any other modules that might be importing it.

The reason is that we may not want this component to be publicly available and just want it for internal use inside module.

To make the component publicly available, we need to export it by adding the component in the exports array. Adding just to the declarations array of module will not make it visible for other modules to import.

10. Conclusion

In this tutorial, we discussed Angular modularity system. We created a module, added a component to this module and imported this module in another module. We recommend you to try in your local. This was a very basic tutorial and we hope will help you to get started.