How to create a shared module in Angular
Creating a shared module in Angular allows you to organize common components, directives, and pipes that multiple feature modules can reuse, reducing code duplication and improving maintainability. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented shared modules in countless Angular applications to manage reusable UI components and services across enterprise applications. From my expertise, the most effective approach is creating a dedicated SharedModule that exports common components and imports essential Angular modules. This method provides centralized component management and consistent imports across feature modules.
Create a SharedModule that declares and exports reusable components while importing common Angular modules.
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { LoaderComponent } from './components/loader.component'
import { ConfirmDialogComponent } from './components/confirm-dialog.component'
import { HighlightDirective } from './directives/highlight.directive'
import { TruncatePipe } from './pipes/truncate.pipe'
@NgModule({
declarations: [
LoaderComponent,
ConfirmDialogComponent,
HighlightDirective,
TruncatePipe
],
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
LoaderComponent,
ConfirmDialogComponent,
HighlightDirective,
TruncatePipe
]
})
export class SharedModule { }
The SharedModule declares components, directives, and pipes in the declarations array, imports essential Angular modules, and exports both the imported modules and declared components. Feature modules can then import SharedModule to access all exported functionality without repeating common imports.
Best Practice Note:
This is the same shared module architecture we use in CoreUI Angular components for organizing reusable UI elements across application modules.