What is a Feature Module?
As your application grows, the Root Module (AppModule) can become a cluttered 'God Object' that is difficult to manage. A Feature Module is an NgModule that helps you partition the application into focused areas. As a Technical Lead, you use feature modules to group related components, directives, and pipes together. This creates clear boundaries between different domains of your app—like a 'User Dashboard' versus an 'Admin Panel'—and is the prerequisite for implementing Lazy Loading.
- Types of Feature Modules
Not all modules serve the same purpose. In a professional architecture, we categorize modules based on their responsibilities.
- Domain Feature Modules: Deliver a specific user experience (e.g.,
EditorModule). They contain components, private services, and models related to that feature. - Routed Feature Modules: Domain modules whose top-level components are the targets of router navigation (used with
loadChildren). - Service Modules: Provide utility services (e.g.,
CoreModulefor authentication or logging). They usually only contain 'providers' and no declarations. - Widget/Shared Modules: Contain reusable components (buttons, spinners) and pipes that are imported by many other feature modules.
- Creating and Importing a Feature Module
When you create a feature module, you typically import CommonModule (which provides *ngIf and *ngFor) instead of BrowserModule (which belongs only in the root).
- The Shared Module Pattern
To avoid importing standard libraries (like Angular Material) into every single feature module, architects often create a SharedModule. This module imports and then re-exports common modules, making them available to any feature module that imports the SharedModule.
Module Communication Table
| Module Type | Imports | Exports | Providers |
|---|---|---|---|
| Root (App) | BrowserModule, FeatureModules | None | Global App Services |
| Feature | CommonModule, SharedModule | Main Feature Component | Feature-specific Services |
| Shared | CommonModule, UI Libraries | UI Components & Directives | Avoid (can cause duplicates) |
| Core | CommonModule | None | Singleton App-wide Services |