Skip to content

Instantly share code, notes, and snippets.

@takahser
Last active November 16, 2017 17:16
Show Gist options
  • Save takahser/af05cd5b3b6a1a122133b21c824f9794 to your computer and use it in GitHub Desktop.
Save takahser/af05cd5b3b6a1a122133b21c824f9794 to your computer and use it in GitHub Desktop.
Angular Modules

Angular Modules

Basic Syntax

Root Module Example:

  import { NgModule } from '@angular/core';
  import { BrowserModule } from '@angular/platform-browser'; // in root modules

  @NgModule({
    imports: [ BrowserModule ], // modules to import
    providers: [ ... ], // services; CAUTION: use 'providers' only in root module
    declarations: [ ... ], // components, directives, pipes that this module contains
    bootstrap: [ AppComponent ] // only in root module
  })
  export class AppModule { }

Feature Module Example:

  import { NgModule } from '@angular/core';
  import { CommonModule } from '@angular/common';; // in feature modules

  @NgModule({
    imports: [ CommonModule ], // modules to import
    providers: [ ... ], // services
    declarations: [ ... ], // directives that this module contains; these are private/module-scoped
    exports: [ ... ], // directives to export with the module (non-private directives)
  })
  export class AppModule { }

Root Modules vs. Feature Modules

2 types of modules:

  • Root modules
  • Feature modules

Root Modules

  • always called AppModule
  • imports BrowserModule (for web projects), which includes the CommonModule already (which is imported into feature modules)
  • 1 per project
  • important for bootstrap process
    • bootstrap happens in main.ts:
  import { AppModule } from './app/app.module';

  platformBrowserDynamic().bootstrapModule(AppModule); // alternatively, the compilation can be part of the build flow (AOT)

Feature Modules

  • : 0-n possible per project
  • imports CommonModule (instead of BrowserModule)
  • the exports keyword can be used to export directives (etc.)
  • types
    • lazy modules := loaded on demand, when user navigates to their routes
    • eager modules := loaded when in root module

References

https://angular-2-training-book.rangle.io/handout/modules/feature-modules.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment