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
- import {
- BrowserModule
- } from '@angular/platform-browser';
- import {
- NgModule
- } from '@angular/core';
- import {
- AppComponent
- } from './app.component';
- @NgModule({
- declarations: [
- AppComponent
- ],
- imports: [
- BrowserModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- 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,
- declarations
It describes what component, directives or pipe belongs to it.
- imports
It describes every module which we are importing into our application.
eg: BrowserModule, HttpModule
- providers
It describes all the services we are importing into our application.
- 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