Angular Modules (NgModule): What They Are and How to Use Them
What are Modules in Angular?
In Angular modules are main way to structure and organize application code.
Every Angular application is a set of NgModules, where one of them is root (AppModule), and others can be feature modules, shared modules, lazy-loaded modules, etc.
Module:
- combines components, directives, pipes, services
- allows managing dependencies and reuse
- helps implement lazy loading and feature division
NgModule Basics
Module is regular class marked with @NgModule decorator:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Main @NgModule Fields
| Field | Description |
|---|---|
declarations | Components, directives and pipes belonging to module |
imports | Modules needed for current module work |
exports | What will be available to other modules |
providers | Services and dependencies |
bootstrap | Main component launched at start (only in AppModule) |
Example: Module Division
src/
├── app/
│ ├── app.module.ts
│ ├── features/
│ │ ├── auth/
│ │ │ ├── auth.module.ts
│ │ │ ├── login.component.ts
│ │ │ └── register.component.ts
auth.module.ts
@NgModule({
declarations: [LoginComponent, RegisterComponent],
imports: [CommonModule, FormsModule],
exports: [LoginComponent] // available in other modules
})
export class AuthModule {}
Angular Module Types
| Type | Purpose |
|---|---|
AppModule | Root module (foundation of entire application) |
Feature Module | For isolating features or sections |
Shared Module | Contains common components, directives, pipes |
Core Module | Contains global services available throughout application |
Lazy Module | Loaded on demand (loading optimization) |
Lazy Loading Modules
Allows loading module only when navigating to it, improving load time:
const routes: Routes = [
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
];
Used for large sections: /admin,/profile, /dashboard
Tip:
Break application into modules to simplify scaling and reuse. One module — one responsibility.