Getting to Know Angular 2’s Module: @NgModule

Getting to know Angular 2 Module @NgModule

Free Course

Getting Started with Angular 2

Angular 2 is the shiny new framework that comes with a lot of new concepts. Learn all the great new features.

Angular 2 has re-introduced the module concept since RC 5 onwards (and now Final Release!). Why do we say reintroduced instead of just introduced? Modules existed in Angular 1!

The initial plan for Angular 2 was to drop the angular.module() and use ES6 modules instead. Throwback to the day when Igor Minar and Tobias Bosch announced the killing of ng.module() during ng-europe conference, Oct 2014.

Angular 2.0 kills off ng.module()

Module in Angular 1

You may skip this part if you are totally new to Angular.

An Angular 1 module is a collection of:

  • services
  • directives
  • controllers
  • filters
  • configuration information.

You syntax will look something like this:

// ng1-my-app.js

...
// Creating a new module
var myModule = angular.module('myModule', []); 

// Defining a new module
myModule
    .value('appName', 'MyCoolApp');
    .controller('controllerName', ControllerFunction)
    .service('serviceName', ServiceFunction)
    .filter('filterName', FilterFunction);
...

// Create a new module that uses myModule
var anotherModule = angular.module('anotherModule', ['myModule']);

Module in Angular 2

Fast forward to Angular 2. Angular Module is now called @NgModule.

Question 1 Why do we need @NgModule?

Short Answer: Angular Modules help to organize an application into cohesive blocks of functionalities and extend it with capabilities from external libraries.

For longer, deeper and more technical answer, check out the explanation in the Angular blog or this document - Understanding @NgModule.

Question 2 But... Don't we have Javascript Modules already? We can already import and export each JavaScript file as a module, right?

Take a deep breath, long answer ahead

In Javascript Modules, every file is one module. In Angular 2, one component is normally a file (if you follow the style guide).

Take for example, you have 10 components in your project, and that translates into 10 files. Now, given that you have another two new components - namely component A and B. These 2 components depend on the 10 components we just described above.

Prior to RC 5, this is how you do it.

// a.component.ts

// import all 10 components here
import { No1Component, No2Component, ... } from './components';

@Component({
  selector: 'a-cmp',
  templateUrl: 'a-cmp.component.html',
  directives:[No1Component, No2Component, ...] // inject all 10 components here
})
export class AComponent {
}

Then, repeat the same process for component B. Now, if we were to create many more components that behave like component A and B, it surely will become cumbersome to keep including these 10 components into every other component. It is certainly not a fun thing to do! However, you can improve the code by creating barrel. Lets look at a more refactored code:

// barrel.ts

// import all 10 components here
import { No1Component, No2Component, ... } from './components';

// export an array of all 10 components
export const groupedComponents = [No1Component, No2Component, ...];

Then change your component A code, to import the barrel to Component A

// a.component.ts

import { groupedComponents } from './barrel';

@Component({
  selector: 'a-cmp',
  templateUrl: 'a-cmp.component.html',
  directives:[groupedComponents] // inject all grouped components here
})
export class AComponent {
}

The code sure does looks neater now but you still have to include groupedComponents in every component that you need it. With @NgModule, what you need to do is this

// a.component.ts

@Component({
  selector: 'a-cmp',
  templateUrl: 'a-cmp.component.html' 
  // no more directives, no more importing component to component
})
export class AComponent {
}

Yes, no more importing components / directives / pipes to each of your components (in our case, component A and B). Instead, we import all to @NgModule and all components / directives / pipes will be available throughout the components under the module.

Every Angular app has at least one module, the root module, conventionally named AppModule.

Here is how a typical AppModule will look like:

// app.module.ts

@NgModule({
    declarations: [ // put all your components / directives / pipes here
        AppComponent, // the root component
        No1Component, No2Component, ... // e.g. put all 10 components here
        AComponent, BComponent, // e.g. put component A and B here
        NiceDirective, 
        AwesomePipe,
    ],
    imports: [ // put all your modules here
        BrowserModule, // Angular 2 out of the box modules
        TranslateModule, // some third party modules / libraries
    ],
    providers: [ // put all your services here
        AwesomeService,
    ],
    bootstrap: [ // The main components to be bootstrapped in main.ts file, normally one only
        AppComponent
    ]
})
export class AppModule { }

Later on, you can bootstrap your application using this app.module.ts.

\\ main.ts

...
platformBrowserDynamic().bootstrapModule(AppModule);
...

There are 3 more less commonly used @NgModule properties (exports, schemas, entryComponents) which I didn't include for the sake of simplicity. Check the documentation here for the full list of propertioes and its description.

How Should We Organize Modules?

There are no standard way to group modules, but the recommendations are:

  1. Features as a module
  2. Shared utilities as a module

Features as a module

Let's say your application has customer and product feature, each feature has some components / pipes / directives. Take for example:

  • Customer: CustomerListComponent, CustomerDetailComponent, CreateCustomerComponent, CustomerService
  • Product: ProductListComponent, ProductDetailComponent, CreateProductComponent, ProductService

Because these features are independent from each other, you may consider to create two modules: CustomerModule and ProductModule, then import these modules to AppModule later.

Shared utilities as a module

For the functions or features that can be shared across modules and application, consider creating a shared module.

A really useful example would be for example, a translation utility in your application (e.g. Translation Service and Translation Pipe. check out my tutorial on implementing language translation in Angular 2). The Translation utility is actually an independent module. By creating a TranslateModule it then can be used by other modules like CustomerModule and ProductModule.

Summary

That it! If you would like to learn how to create a shared module, check out my article, as it gives you a step by step guide on creating your own TranslateModule.

If you need more in depth knowledge about@NgModule, checkout the official documentation:

  1. Angular Module FAQs
  2. Angular Modules @NgModule

Jecelyn Yeen

Coder. Diver. Board Game Lover.

Speak English, Mandarin, JavaScript, Typescript, C# and more.

Problem solver at @iflix.