What are Modules in Angular and How Are They Used?

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

FieldDescription
declarationsComponents, directives and pipes belonging to module
importsModules needed for current module work
exportsWhat will be available to other modules
providersServices and dependencies
bootstrapMain 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

TypePurpose
AppModuleRoot module (foundation of entire application)
Feature ModuleFor isolating features or sections
Shared ModuleContains common components, directives, pipes
Core ModuleContains global services available throughout application
Lazy ModuleLoaded 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.