ng-book 2 author’s summary of ngModule


Angular RC5 introduced NgModule – NgModule is a way to organize your dependencies for 1. the compiler and 2. dependency injection.

I’m going to quickly explain why we need NgModules and how to work with them. In five minutes, you’ll understand NgModules enough to put it in your own apps.

The context here is to think about the two roles of the compiler and dependency injection in Angular. Briefly, Angular needs to know what components define valid tags and where dependencies are coming from.

NgModule vs. JavaScript Modules

You might be asking, why do we need a new module system at all? Why can’t we just use ES6/TypeScript modules?

The reason is, whereas using import will load code modules into JavaScript, the NgModule system is a way of organizing dependencies within the Angular framework. Specifically around what tags are compiled and what dependencies should be injected.

The Compiler and Components

For the compiler, when you have an Angular template that has custom tags you have to tell the compiler what tags are valid (and what functionality should be attached to them).

E.g. if we have this component:

  selector: 'hello-world',
  template: `
Hello world
` }) class HelloWorld { }

We want the compiler to know that the following HTML should use our hello-world component (and that hello-world isn’t some random invalid tag):

In Angular 1, the hello-world selector would have been registered globally which is convenient until your app grows and you start having naming conflicts. For instance, it’s not hard to imagine two open-source projects that might use the same selector.

If you’ve been using Angular 2 since the earlier versions, you may remember that previous versions required that you specify a directives option in your @Component annotation. This was good in that it was less “magic” and removed the surface area for conflicts. The problem was it’s a bit onerous to specify all directives necessary for all components.

Instead, using NgModules we can tell Angular what components are dependencies at a “module” level. More on this in a second.

Dependency Injection and Providers

Recall that Dependency Injection (DI) is an organized way to make dependencies available across our app. It’s an improvement over simply importing code because we have a standardized way to share singletons, create factories, and override dependencies at testing time.

In earlier versions of Angular 2 we had to specify all things-that-would-be-injected (with providers) as an argument to the bootstrap function.

Note on terminology: a provider provides (creates, instantiates, etc.) the injectable (the thing you want). In Angular when you want to access an injectable you inject a dependency into a function and Angular’s dependency injection framework will locate it and provide it to you.

Now with NgModule each provider is specified as part of a module.

NgModules 101

So now that we understand why we need NgModules how do we actually use it? Here’s the simplest case:

// app.ts

  imports: [ BrowserModule ],
  declarations: [ HelloWorld ],
  bootstrap: [ HelloWorld ]
class HelloWorldAppModule {}


In this case we’re defining a class HelloWorldAppModule – this is going to be the entry point of our application. Starting with RC5, instead of bootstrapping our app with a component, we bootstrap a module with bootstrapModule, as you see here.

NgModules can import other modules as dependencies. We’re going to be running this app in our browser and so we import BrowserModule.

We want to use the HelloWorld component in this app. Here’s a key thing to keep in mind: Every component must be declared in some NgModule. Here we put HelloWorld into the declarations of this NgModule.

We say the HelloWorld component belongs to the HelloWorldAppModule – every component can belong to only one NgModule.

You’ll often group multiple components together into one NgModule, much like you might use a namespace in a language like Java.

If you want to bootstrap this module (that is, use this module as the entry point for an application), then you provide a bootstrap key which specifies the component that will be used as the entry-point component for this module.

So in this case we’re going to bootstrap the HelloWorld component as the root component. However, the bootstrap key is optional if you’re creating a module that doesn’t need to be the entry-point of an application.

Component Visibility

In order to use any component, the current NgModule has to know about it. For instance, say we wanted to use a user-greeting component in our hello-world component like this:

  <!-- hello-world template -->
greeting> world

For any component to use another component it must be accessible via the NgModule system. There are two ways to make this happen:

  1. Either the user-greeting component is part of the same NgModule (e.g. HelloWorldAppModule) or
  2. The HelloWorldAppModule imports the module that the UserGreeting component is in.

Let’s say we want to go the second route. Here’s the implementation of our UserGreeting component along with the UserGreetingModule:

  selector: 'user-greeting',
  template: `<span>hello</span>`
class UserGreeting {

  declarations: [ UserGreeting ],
  exports: [ UserGreeting ]
export class UserGreetingModule {}

Notice here that we added a new key: exports. Think of exports as the list of public components for this NgModule. The implication here is that you can easily have private components by simply not listing them in exports.

If you forget to put your component in both declarations and exports (and then try to use it in another module via importsit won’t work. In order to use a component in another module via imports you must put your component in both places.

Now we can use this in our HelloWorld component by importing it into the HelloWorldAppModule like so:

// updated HelloWorldAppModule

  declarations: [ HelloWorld ],
  imports: [ BrowserModule, UserGreetingModule ], // <-- added
  bootstrap: [ HelloWorld ],
class HelloWorldAppModule {}

Specifying Providers

Specifying providers of injectable things is done by adding them to the providers key of a NgModule.

For instance, say we have this simple service:

export class ApiService {
  get(): void {
    console.log('Getting resource...');

and we want to be able to inject it on a component like this:

class ApiDataComponent {
  constructor(private apiService: ApiService) {

  getData(): void {

To do this with NgModule is easy: we pass ApiService to the providers key of the module:

  declarations: [ ApiDataComponent ],
  providers: [ ApiService ]   // <-- here
class ApiAppModule {}

the constant ApiService here is the shorthand version of using provide like this:

  declarations: [ ApiDataComponent ],
  providers: [
    provide(ApiService, { useClass: ApiService })
class ApiAppModule {}

We’re telling Angular that when the ApiService is to be injected, create and maintain a singleton instance of that class and pass it in the injection. There are lots of different ways to inject things, and we go over all of them in the book.

In order to use those providers from another module, you guessed it, you have to import that module.

Because the ApiDataComponent and ApiService are in the same NgModule the ApiDataComponent is able to inject the ApiService. If they were in different modules, then you would need to import the module containing ApiService into the ApiAppModule.


New in RC5 we have a TestBed library from @angular/core/testing. When you write your tests you have to configure an NgModule there. Thankfully, TestBed provides a configureTestingModule option which takes an NgModule configuration and applies to the components created in your test.

For instance, here’s how we might configure our NgModule to use the above samples:

describe('DemoFormSku Component', () => {

  beforeEach(() => {
      imports: [

  // tests here...


When using TestBed.configureTestingModule. You can also override your providers or put custom testing components in declarations etc. Again, we have complete examples of these in the sample code for the book.

NgModules Tips and Gotchas

The community conventions around NgModules are still being worked out. That said, my advice is to organize your NgModules like you organize your packages already. Group ideas together and then import the top-level modules into your app module at bootstrap time.

There are two “gotchas” I want you to keep in mind:

First, if you want to use a component in another module, make sure you add it to declarations and exportsbefore you put it in imports (this bit me several times).

Second, you can find the common directives like NgIfNgFor, etc. by import { CommonModule } from '@angular/common'. This happens by default when using BrowserModule but if you’re writing tests you may not import BrowserModule and thus you’d get an error.

The advice generalizes to: make sure you understand the module dependency flow, especially when testing. Failure to import modules properly will result in failing tests (and the error messages aren’t always clear).


NgModules is a great way to clearly specify which dependencies your components require. While it is slightly more ceremony up-front, the long-term effect is that we’re able to organize dependencies explicitly and minimize conflicts – which is a requirement for larger apps.


Angular 2 – Jaime Vintharas answers my Http/JSON headers question


I read your Updating your Angular 2 app from rc4 to rc5 post and have been looking at your PeopleService class in your consuming real data with http repo in github.


Hi Charles! ^_^

That’s to account for how different browsers behave and because it’s the right thing to do since we expect the response to be json.
If I omit the Accept: application/json header in Chrome, Chrome will include the Accept header with a value of */* and the API will return it’s preferred media type which in this case is application/json. (It’s up to the API implementer to make that decision when they’re implementing their API). So, in this case, even if I don’t add a header explicitly everything works as fine.
If I omit the Accept header in Firefox, Firefox will include the Accept header with a value of text/html. The star wars API is configured to respond with help web pages for any given resource when the media type is text/html. That you can have different representations for the same resource is a pretty core principle of RESTful APIs, so it’s actually a pretty neat API in that sense. For the case of our application though this means that, all of the sudden, we’re getting an html response that we try to parse as if it were JSON and it crashes our app.
So that’s why we have the getHeaders in the example, and explicitly setting the Accept header to application/json. When you are consuming a REST API you need to specify with media types you can consume so that the API provider can either give you the right representation or an error message that you can properly handle when the representation is not available (this is known as *Content Negotiation). In absence of that each browser is going to use it’s own defaults and each API implementer is going to respond based on how the implementers thought best.
Hope it helped, ^_^
Have a nice day!
Kind Regards,
Content negotiation (from Wikipedia) are mechanisms defined as a part of HTTP that make it possible to serve different versions of a document (or more generally, representations of a resource) at the same URI, so that user agents can specify which version fit their capabilities the best. One classical use of this mechanism is to serve an image in GIF or PNG format, so that a browser that cannot display PNG images (e.g. MS Internet Explorer 4) will be served the GIF version.
HTTP provides for several different content negotiation mechanisms including: server-driven (or proactive), agent-driven (or reactive), transparent, and/or hybrid combinations thereof.

Angular 2 Lifecycle Hooks

Lifecycle Hooks Angular 2 docs

(From halfway down the page) We turn to ngOnInit for two main reasons:

  1. To perform complex initializations shortly after construction
  2. To set up the component after Angular sets the input properties

HTTP client – oninit Angular 2 docs

Although at runtime the component requests heroes immediately after creation, we do not call the service’s getmethod in the component’s constructor. We call it inside the ngOnInit lifecycle hook instead and count on Angular to call ngOnInit when it instantiates this component.

This is a best practice. Components are easier to test and debug when their constructors are simple and all real work (especially calling a remote server) is handled in a separate method.

Angular 2 – 2.0 Final, RC 6, and RC 5

List of Thoughtram articles leading up to Angular 2 Final release by Pascal Precht (September, 2016)

ng2 Final – QA with key people Igor, Rob, Brad, by Juri Strumpflohner (September, 2016)

Starting an Angular 2 RC.6 project by Yakov Fain (September, 2016)

Updating Your Angular 2 App From RC4 to RC5: A Practical Guide by Jaime Vintharas (August, 2016) Useful post AND comments about modules (HttpModule is what I was curious about) and how import statements change from rc4 to rc5 to accommodate NgModule concept.

The Code sample on github (Updated to rc5 in August, 2016)

Angular 2 JumpStart with TypeScript by Dan Wahlin (Updated August, 2016)

Angular 2 – NgModule and Compilation

Angular 2 ngModule series by John Papa (September, 2016)

NgModuleMetadata from docs

ng-book 2 authors’ summary of ngModule by Nate, Felipe, Ari, & Carlos (August, 2016)

Updating Your Angular 2 App From RC4 to RC5: A Practical Guide by Jaime Vintharas (August, 2016) Useful post AND comments about modules (HttpModule is what I was curious about) and how import statements change from rc4 to rc5 to accommodate NgModule concept.

NgModule on large project – Rob Wormald reply (August, 2016)

Angular 2 RC5 – NgModules, Lazy Loading and AoT compilation

Angular 2 NgModule Intro – Ahead Of Time Compilation And Lazy Loading – Avoid Common Pitfalls by Iurii Kyrylenko, Angular University (August, 2016)

Angular Modules (NgModule) from docs

Angular Modules (NgModules) have landed in Angular RC5!

Just in Time (JIT) Compilation – good choice during development

Ahead of Time (AOT) Compilation – Ahead of Time compiled applications benefit from decreased load time and increased performance

Angular 2 : Organization Using {barrels} by Shayne Boyer (May, 2016)

What are all the index.ts used for? stackoverflow (June, 2016)

Barrel Issues (July, 2016):


Cooking with ASP.NET Core and Angular 2 by Ed Charbeneau (November, 2016)

Writing Clean Code in ASP.NET Core with Dependency Injection Nice explanation of whi it makes sense to use repository instead of entire dbContext  – by Steve Smith (May, 2016)

Simple tutorials:

ASP.NET Core home page

Introduction to ASP.NET Core by Daniel Roth, Rick Anderson and Shaun Luttin (July, 2016)

Introducing ASP.NET Core 1.0 (video)  Speakers: Scott Hanselman, Scott Hunter (March, 31, 2016)

ASP.NET Core MVC – formatting response data by Steve Smith