Angular 2 – Modules

What is an Angular Module?

In Angular, a module is a mechanism or process to bind all of your components, directives, pipes and services that are inter related to each other, in such a way that can be combined with other modules to create an application.

Angular Modules help to organize & maintain our application into cohesive blocks of functionalities and extend it with capabilities from external libraries. Angular apps are modular and Angular has its own modularity system by default called NgModules.

Every Angular application has at least one NgModule class, the root module, normally we called as AppModule.  As per application need we can create our own modules depending on application need.

The following code will be present in the app.module.ts file.

Now lets understand each lines,

Decorator : @NgModule ({…})

Here  @NgModule ({…}) is an angular decorator function that takes a metadata object whose properties describe in the module.

Decorators are functions that modify the normal JavaScript classes definition. Angular has many decorators that attach metadata to classes so that angular knows what those classes mean and how they should work.

 

The most Important properties of Decorators functions are:

1. imports:

As the name implies  all other modules whose exported classes that needed by component templates, declared in this imports.

2. providers:

It is a creators of services that this module contributes to the global collection of services; they become accessible in all parts of the app.

3. declarations:

In declarations we define all the view classes(like Components) that belong to this module.  Angular has three kinds of view classes that are components, directives, and pipes.

4. exports:

To make module accessible and visible to other modules, need to export first, so that other module can import it’s functionality.

5. bootstrap:

in bootstrap we define the application root app, so that it can bootstrap that root app on view. This is the root component of application view that rendered on view,  It is the hosts or parent of all other app views, all other views rendered on call on this root component.  Only the root module should set this bootstrap property.

Here The export of AppComponent is just to show how to use the exports array to export a component; it isn’t actually necessary in for the AppComponent. Actually  a root module has no reason to export anything because other components don’t need to import the parent or root module.