0
0
Angularframework~5 mins

NgModule decorator and metadata in Angular

Choose your learning style9 modes available
Introduction

The NgModule decorator helps organize your Angular app by grouping components, directives, and services together.

When you want to group related components and services in one place.
When you need to tell Angular which components belong to your app.
When you want to import other modules to use their features.
When you want to make some components or services available outside the module.
When you want to bootstrap the main component to start your app.
Syntax
Angular
@NgModule({
  declarations: [Component1, Component2],
  imports: [OtherModule],
  providers: [Service1],
  exports: [Component1],
  bootstrap: [AppComponent]
})
export class AppModule {}

declarations lists components, directives, and pipes that belong to this module.

imports includes other modules whose features you want to use.

Examples
This example declares two components and bootstraps the HomeComponent to start the app.
Angular
@NgModule({
  declarations: [HomeComponent, AboutComponent],
  imports: [BrowserModule],
  bootstrap: [HomeComponent]
})
export class AppModule {}
This module declares a login component, imports form features, provides an authentication service, and exports the login component for use in other modules.
Angular
@NgModule({
  declarations: [LoginComponent],
  imports: [FormsModule],
  providers: [AuthService],
  exports: [LoginComponent]
})
export class AuthModule {}
Sample Program

This is a simple Angular module that groups two components and starts the app with AppComponent.

Angular
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  declarations: [AppComponent, HelloComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule {}
OutputSuccess
Important Notes

Every Angular app has at least one module called the root module.

Use declarations only for components, directives, and pipes.

Services go in providers if you want to provide them at the module level.

Summary

NgModule groups related parts of your Angular app.

It uses metadata like declarations, imports, providers, and bootstrap.

This helps Angular know what to load and how to start your app.