Angular Modules
In Angular, modules help organize your application into cohesive blocks of functionality. Every Angular app has at least one module called the root module, and additional modules can be created for features, shared functionality, or lazy loading.
1. Root Module (AppModule)
Every Angular application starts with a root module called AppModule.
It is defined in app.module.ts.
Example:
- declarations – Components, directives, and pipes that belong to this module
- imports – Other modules required by this module
- providers – Services available to the module
- bootstrap – Root component that Angular loads first
2. Feature Modules
Feature modules are used to organize related components, services, and other code into a logical group.
Example: UserModule, ProductModule.
Benefits:
- Keeps the app organized
- Improves maintainability
- Makes code reusable
3. Shared Modules
Shared modules contain components, directives, pipes, or services that are used across multiple modules.
Example: SharedModule can include a HeaderComponent, FooterComponent, and commonly used pipes.
4. Lazy Loading Modules
Lazy loading modules improves performance by loading modules only when needed instead of loading everything at startup.
Example:
app-routing.module.ts
Benefits:
- Reduces initial load time
- Improves app scalability
5. NgModule Metadata
Every module in Angular uses the @NgModule decorator with metadata:
- declarations – Components, directives, and pipes inside the module
- imports – Other modules needed
- exports – Components, directives, and pipes made available to other modules
- providers – Services for dependency injection
- bootstrap – Root component to load at startup (only in root module)
Summary
- Angular modules organize the application into cohesive blocks.
- AppModule is the root module loaded at startup.
- Feature modules group related functionality.
- Shared modules provide reusable components and services.
- Lazy loading modules improve performance.
@NgModulemetadata defines declarations, imports, exports, providers, and bootstrap components.