What is Shared Module in Angular: Explanation and Example
SharedModule in Angular is a module created to hold common components, directives, and pipes that are used across multiple feature modules. It helps avoid repeating code by centralizing reusable parts and then importing this module wherever needed.How It Works
Think of a shared module like a toolbox you keep in one place but use in many rooms of your house. Instead of buying a new hammer or screwdriver for each room, you keep one set in the toolbox and bring it wherever you need it.
In Angular, a SharedModule collects components, directives, and pipes that many parts of your app use. You declare and export these reusable pieces inside the shared module. Then, other feature modules import the shared module to get access to those pieces without rewriting or redeclaring them.
This keeps your app organized and reduces duplication, making it easier to maintain and update common functionality in one place.
Example
This example shows a simple SharedModule that exports a common component and a pipe. Other modules can import this shared module to use them.
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HighlightDirective } from './highlight.directive'; import { FormatDatePipe } from './format-date.pipe'; import { ButtonComponent } from './button/button.component'; @NgModule({ declarations: [HighlightDirective, FormatDatePipe, ButtonComponent], imports: [CommonModule], exports: [HighlightDirective, FormatDatePipe, ButtonComponent, CommonModule] }) export class SharedModule {} // Usage in a feature module import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { FeatureComponent } from './feature.component'; @NgModule({ declarations: [FeatureComponent], imports: [SharedModule] }) export class FeatureModule {}
When to Use
Use a SharedModule when you have components, directives, or pipes that multiple feature modules need. For example:
- Buttons, icons, or UI widgets used in many places
- Custom pipes for formatting dates or text
- Directives for common behaviors like highlighting or tooltips
This avoids repeating code and keeps your app DRY (Don't Repeat Yourself). It also makes updates easier because you change the shared code in one place.
Key Points
- A shared module groups reusable Angular parts for easy sharing.
- It exports components, directives, pipes, and modules like
CommonModule. - Feature modules import the shared module to use its exports.
- Helps keep code clean, organized, and maintainable.
- Do not provide services in shared modules to avoid multiple instances.