What is @NgModule actually in Angular?

manohar picture manohar · Nov 3, 2016 · Viewed 18.8k times · Source

I am new to Angular 2.

What is @NgModule actually in Angular 2? I referred through the official documentation by the Angular. But I didn't have any clarity.

Answer

Rash picture Rash · Jan 9, 2019

As applications started to become more and more complex, it became evident that all applications should be divided into modules. Each module is a small mini application on its own, but now you can bundle all these mini-applications to make your larger application.

enter image description here

Angular's answer to creating modules is @NgModule. This is the tag that allows you to create a module. A module in angular consists of components or other module's components along with other stuff that we will not talk about.

So let's say your application has two big sections - wishlist, and cart. You can create modules for each of them - WishlistModule and CartModule. In WishlistModule you will have several components (decorated as @NgComponent) such as displaying items, dragging and dropping items, etc. Similarly for CartModule.

To create modules, you will need to use @NgModule like below.

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

import { WishlistMainComponent }   from './wishlistMain.component';
import { WishlistShowComponent }   from './wishlistShow.component';
import { WishlistDragComponent }   from './wishlistDrag.component';
import { HeaderModule }   from './header.module';

@NgModule({
  imports:      [ 
    BrowserModule,
    HeaderModule
  ],
  declarations: [
    WishlistMainComponent, WishlistShowComponent, WishlistDragComponent
  ],
  bootstrap: [ WishlistMainComponent ]
})
export class WishlistModule { }

As other answers have already pointed out, @NgModule does a lot behind the scenes, but in simple terms, it declares a module. It is sort of like a Java class, and whatever you pass in the bootstrap option is like the main() method.

A module (or @NgModule) in itself is nothing but just a briefcase containing a bunch of components, and really, the components are what actually your application is made of. A component defines a tag e.g. <wishlist></wishlist> where angular puts all your wishlist code. The module is just under which the component lives, and if you wish to use an external component, then you can only do so by importing its module, just like Java class and methods.