Ang2

Modularizing Angular 2 Apps with NgModule

Organize application functionality by splitting them into modular chunks.

Eric Simons Up to date (Jun '17) Angular 2
PRO

The complexity and size of real world codebases for Javascript apps continues to grow larger and larger every year. To combat this, codebases are often "modularized" for two primary reasons:

  1. To provide a clear separation of concerns for the application's functionality
  2. To easily implement app performance upgrades like code splitting and AoT compilation

In fact, modularization is now such an important part of building web apps that Angular 2 requires you to architect your applications with it out of the box!

While Angular 1 also had a module system, it was often ignored by developers as it often didn't provide enough advantages to make it completely necessary. With Angular 2 this is no longer the case.

Introducing NgModule

From the Angular 2 docs:

Angular Modules help organize an application into cohesive blocks of functionality.

Every time you add a new feature set into your application, it's a good idea to create a new module to contain it. However, you want to avoid creating unnecessary modules as well, so understanding when to create modules is a bit nuanced. We'll cover this in detail a bit later when we show real world examples.

The root AppModule

Per the Angular Style Guide, every Angular 2 app needs to have a root module called AppModule that is responsible for importing all other modules & functionality that is required for the app to start. The Angular Team has an excellent resource that describes it in detail:

It's worth noting that Angular services that need to act like singletons (which most services do) should be imported in the AppModule to ensure there is only one instance ever created during the lifecycle of the application.

If we take a look at our previous examples you'll see how we defined the app module in app/app.module.ts:

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'

import { AppComponent } from './app.component';
import { HeaderComponent, SharedModule } from './shared/index';

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

You can view the working demo here:

In the next chapter we're going to cover a critical type of module that you'll need to create in any reasonably sized application: the shared module.

 

I finished! On to the next chapter