Hello Friends, In this tutorial we are going to learn Modules in Angular 2. In the Last Session, we have seen how to setup environment for creating a Simple Hello World application. Modules provide a mechanism to group components, directives, pipes and services that are related in such a way so that it can be combined with other modules to create an application.

Introduction to Modules:

A module is a way to group components, directives, pipes, and services that are related in such a way so that it can be combined with other modules to create an application. Modules enable you to separate the functionality of your application by creating a logical boundary. You can think module as a class where a class is made up of different components like property, methods, and variables.We can define methods as public or private where public methods can be used by other classes and the privates remain hidden. The module works in the same way where the export element can expose component, directives, and services to other modules. While the other that are not exported used inside the module itself and these can be accessed by other modules.

Angular 2 Modules are classes decorated with @NgModule. @NgModule is used to attach module metadata to the class. A metadata defines following terms:

  • Which component, directive, pipes, and services belong to that module.
  • Make some classes public so that other module can use them.
  • Imports other modules with components, directives, and pipes that are required by the component in the current module.
  • Provides services at the application level that can be used by any application.

The following block of code is an example of module which is present in app.module.ts file.

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { AppComponent } from './app.component';

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

Les’s define each line of code in detail:

1-> import statement is used to import existing module’s functionality. The first three statements are used to import NgModule, BrowserModule and AppComponent module into the current module.

2> @NgModule decorator requires at least three properties:

  • Imports: This property expects an array of the module that needs to import into current module.
  • declarations: This property expects an array of component, directive, and pipes.
  • bootstrap: This specifies the root component of our module.

Every application has an at least single module that is called the root module. As the application grows you can add your module and import that module into your root module.

View More:


Hope you understand what are Modules in Angular 2. I would appreciate your feedback, comments, and suggestions.

Thank You,

Leave a Comment