Angular 2.0 – Modules

Read Angular 2.0 Introduction

Modules

Angular approach is a modular approach. So Angular applications are modular. And its modules are called as Angular Modules or NgModules.

All Angular apps have atleast one module called the root module, or conventionally called as AppModule. (In small applications generally only one module is there i.e., AppModule). Other modules are called feature modules.

A Module have —— a class + ‘@NgModule’ decorator. Read about Decorators.
NgModule takes single metadata object. This object have several properties that describes the module.

Its Properties are :

  • declarations
  • exports
  • imports
  • providers
  • bootstrap

Tip:
It is not mandatory that all modules should define all the above properties. They can have 2 or 3 or whatever application demands.

declarations

  • They are the view classes (components, directives, pipes) belong to that module.




exports

imports

  • Other modules whose classes we are going to use in the current module’s component.

providers

bootstrap

Simple Structure of Module

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

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

Angular module system and Javascript module system are totally different and unrelated.
In Angular Module is a class decorated with @NgModule decorator.

In javascript, each file is module. And all the objects defined in the file are belong to that particular module. Some objects that are needed outside that module are declared public with the help of ‘export’ keyword.

A module can use other module’s public objects by using import statements.

In Angular we use both. (i.e., Angular module system as well as Javascript module system).
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
export class AppModule { }

These are Javascript import/export statements.

imports: [ BrowserModule ],
This imports is the metadata of @NgModule, means It is an Angular thing.

So Don’t confuse between import/export and imports/exports keyword. I hope it is clear a little with the above examples rest will understood with time and experience.