The @NgModule is a new decorator. This module is recently added in Angular 2.
The @NgModule is a class and work with the @NgModule decorator function. @NgModule takes a metadata object that tells Angular “how to compile and run module code”.
The @NgModules page guides you from the most elementary @NgModule to a multi-faceted sample with lazy modules.
The @NgModule main use to simplify the way you define and manage the dependencies in your applications and using @NgModule you can consolidate different components and services into cohesive blocks of functionality.
The Basic Example of @NgModule as,
The @NgModule is a way to organize your dependencies for
2. Dependency Injection
The declarations of @NgModule.declarations as,
The @NgModule providers as,
The @NgModule exporting as,
Why Angular 2 modules needed?
An Angular @NgModule allows us to define a context for compiling templates.
1. Easy to use Components
2. Easy to use Directives
3. Easy to use Pipes
4. Providers’ Inheritance
5. Library Architecture
6. Easy to migrate from angular.module()
7. So on
What is a Root Module?
Each application only has one root module and each component, directive and pipe should only be associated to a single module. This one is the main reason.
How Should We Organize Modules?
There are no standard ways to group modules, but the recommendations are,
1. Features as a module
2. Shared utilities as a module
For example, suppose that your application has customer, product and feature. Each module has some components, directives and pipes.
For the functions or features that can be shared across modules and application, consider creating a shared module.
How to declaration Module?
What is One Root Module?
When we create an Angular 2 app, we define a root module. We learned about this in the previous post. This root module is defined with @NgModule and works quite well for small apps.
Our root module declares our components, pipes and directives.
Our root module imports common features from the Angular 2 BrowserModule, FormsModule, and HttpModule.
Final Conclusions are,
1. The Use of NgModule.providers
a. Remove Component.providers
2. Use NgModule.declarations
a. Remove Component.directives/pipes
3. Keep a single scope
4. Use modules
a. Http, Forms, Router, and so on.
5. Make modules
6. Module as a Library