Back to course

NgModules: The Building Blocks

The Complete Angular Developer: From Zero to Hero

7. NgModules: The Building Blocks

Angular applications are modular. NgModules (@NgModule) are containers that group related components, services, and pipes, defining how Angular should compile and launch parts of the application.

The @NgModule Decorator

An NgModule is a class decorated with @NgModule, which takes a single metadata object.

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

@NgModule({ declarations: [AppComponent, /* Other Components, Directives, Pipes /], imports: [BrowserModule, / Other Angular or custom Modules /], providers: [/ Services go here */], bootstrap: [AppComponent] // Only in the Root Module }) export class AppModule { }

Key Properties of @NgModule

  1. declarations: Lists the components, directives, and pipes that belong to this module. Important: Items can only be declared in one module.
  2. imports: Imports other NgModules whose exported classes (components, directives, pipes) are required by components in this module.
  3. providers: Lists the services that should be made available via Dependency Injection (DI) to the entire application (or just this module, depending on scope).
  4. exports: Lists the subset of components, directives, and pipes that should be accessible to other modules that import this one (e.g., if we create a SharedModule).
  5. bootstrap: (Used only in the root module, AppModule). Identifies the root component that Angular should load when bootstrapping the application.