Ang2
Modularizing Angular 2 Apps with NgModule
  •  

Creating the SharedModule

PRO

Creating a 'SharedModule' is part of the Angular Style Guide for a reason — if you don't create one for your application up front, you'll almost certainly have to refactor your application to use it once you have any meaningful amount of functionality.

Why is this? Because if you don't, you'll run into circular dependency issues. What this means is that if module 1 tries to import something (lets say a header component) from module 2, module 1 might actually be a dependency of module 2. So you have a circular dependency between these two modules that will never be able to resolve!

The SharedModule typically consists of common Angular specific modules (CommonModule, FormsModule, etc) as well as any components, services, etc that you want to reuse across your application.

Per the Angular Style Guide, the shared module should be created in the app/shared/ folder:

app/shared/shared.module.ts

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';


@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    HttpModule,
    RouterModule
  ],
  declarations: [],
  exports: [
    CommonModule,
    FormsModule,
    HttpModule,
    RouterModule
  ]
})
export class SharedModule {}

You can view the working example here:

Shared Module

Now any new modules can simply import SharedModule instead of having to manually import all of Angular's modules as well as any shared components and services!