Angular - Understanding NgModule

In this article, we will try to understand NgModule – Why and How to use it?

Introduction

If you are new to Angular, please follow the previous article.

When we create an Angular application through Angular CLI, we can see NgModule in an app.module file – which is imported from @angular/core module.

In this article, we will try to understand NgModule – Why and How to use it?

app.module.ts file

  1. import {  
  2.     BrowserModule  
  3. } from '@angular/platform-browser';  
  4. import {  
  5.     NgModule  
  6. } from '@angular/core';  
  7. import {  
  8.     AppComponent  
  9. } from './app.component';  
  10. @NgModule({  
  11.     declarations: [  
  12.         AppComponent  
  13.     ],  
  14.     imports: [  
  15.         BrowserModule  
  16.     ],  
  17.     providers: [],  
  18.     bootstrap: [AppComponent]  
  19. })  
  20. export class AppModule {}  

Why do we use NgModule?

When we write any classes in C#, we use namespaces to group them; so, here NgModule is used for the same purpose -- to group components and/or services which belongstogether.

@NgModule takes a metadata object that describes how to compile a component's template and how to create an injector at runtime.

How to use it?

@NgModule has many different arrays inside it,

  1. declarations
    It describes what component, directives or pipe belongs to it.

  2. imports
    It describes every module which we are importing into our application.
    eg: BrowserModule, HttpModule

  3. providers
    It describes all the services we are importing into our application.

  4. bootstrap
    It describes which component which will be bootstrapped into the application when it starts.

References

  • https://angular.io/guide/ngmodule-faq
  • https://angular.io/guide/ngmodules
  • https://medium.com/@cyrilletuzi/understanding-angular-modules-ngmodule-and-their-scopes-81e4ed6f7407