0
0
Angularframework~15 mins

Shared modules for reusable components in Angular - Deep Dive

Choose your learning style9 modes available
Overview - Shared modules for reusable components
What is it?
Shared modules in Angular are special containers where you put components, directives, and pipes that you want to use in many places across your app. Instead of rewriting or copying code, you import this shared module wherever you need those pieces. This helps keep your app organized and avoids repeating yourself.
Why it matters
Without shared modules, you would have to duplicate components or import them individually in many places, making your app messy and hard to maintain. Shared modules save time, reduce errors, and make your app easier to update because you change code in one place and it affects everywhere. This leads to faster development and better teamwork.
Where it fits
Before learning shared modules, you should understand Angular modules (NgModules) and how components work. After mastering shared modules, you can explore feature modules, lazy loading, and advanced dependency injection to build scalable apps.
Mental Model
Core Idea
A shared module bundles reusable Angular components, directives, and pipes so they can be easily imported and used across multiple parts of an app.
Think of it like...
Think of a shared module like a toolbox you carry to different rooms in your house. Instead of buying a new hammer or screwdriver for each room, you bring your toolbox with all the tools you need. This way, you reuse the same tools everywhere without clutter.
┌─────────────────────────────┐
│       Shared Module          │
│ ┌───────────────┐           │
│ │ Component A   │           │
│ │ Directive B   │  <--------│-- Imported by multiple feature modules
│ │ Pipe C        │           │
│ └───────────────┘           │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Angular Modules Basics
🤔
Concept: Learn what Angular modules (NgModules) are and how they organize code.
Angular modules group related components, directives, and pipes. Each module has metadata that tells Angular what it contains and what it exports. This helps Angular know what parts belong together and how to load them.
Result
You can create a module that holds components and use it to organize your app logically.
Understanding Angular modules is essential because shared modules are just special NgModules designed for reuse.
2
FoundationCreating Simple Components
🤔
Concept: Learn how to build Angular components that can be reused.
Components are the building blocks of Angular apps. Each component has a template (HTML), styles (CSS), and logic (TypeScript). You create components to represent UI parts like buttons, forms, or lists.
Result
You can create a component that displays a button or message.
Knowing how to create components is necessary before sharing them across modules.
3
IntermediateBuilding a Shared Module
🤔Before reading on: Do you think a shared module should declare components only, or also export them? Commit to your answer.
Concept: Learn how to declare and export components in a shared module so other modules can use them.
In a shared module, you declare components, directives, and pipes you want to reuse. Then you export them so other modules that import this shared module can use those pieces. You also import common Angular modules like CommonModule to support basic Angular features.
Result
A shared module that bundles reusable components and makes them available to other modules.
Knowing that exporting is necessary for reuse prevents the common mistake of components not appearing in other modules.
4
IntermediateImporting Shared Modules in Feature Modules
🤔Before reading on: If you import a shared module in a feature module, do you need to redeclare its components? Commit to your answer.
Concept: Learn how to import a shared module into feature modules to use its components without redeclaring them.
Feature modules import the shared module in their imports array. This gives them access to all exported components, directives, and pipes from the shared module. You do NOT redeclare shared components in feature modules; importing is enough.
Result
Feature modules can use shared components seamlessly by importing the shared module.
Understanding import vs declare avoids duplication and errors in Angular module setup.
5
IntermediateAvoiding Common Shared Module Pitfalls
🤔Before reading on: Should you provide services in a shared module? Commit to your answer.
Concept: Learn best practices about what to include in shared modules and what to avoid, like service providers.
Shared modules should contain reusable UI components, directives, and pipes. Avoid providing services here because it can cause multiple instances and unexpected behavior. Services belong in core modules or provided in root.
Result
A clean shared module that avoids service duplication and keeps components reusable.
Knowing where to provide services prevents bugs related to multiple service instances.
6
AdvancedOptimizing Shared Modules for Performance
🤔Before reading on: Does importing a shared module multiple times increase bundle size? Commit to your answer.
Concept: Learn how Angular handles shared modules in terms of bundle size and how to optimize imports.
Angular merges imported modules during build, so importing a shared module in many feature modules does not duplicate code in the final bundle. However, importing large shared modules everywhere can increase initial load time. Splitting shared modules or using lazy loading can optimize performance.
Result
Efficient app bundles with reusable components without code duplication.
Understanding Angular's module merging helps balance reuse and performance.
7
ExpertAdvanced Patterns: Shared Modules and Standalone Components
🤔Before reading on: Can standalone components replace shared modules? Commit to your answer.
Concept: Explore how Angular's standalone components feature changes the role of shared modules.
Standalone components can be used without declaring them in modules, reducing the need for shared modules. However, shared modules still help group reusable components, especially when you want to bundle multiple pieces together. Combining standalone components with shared modules offers flexible reuse patterns.
Result
Modern Angular apps can choose between shared modules and standalone components for reuse.
Knowing the evolving Angular features helps you choose the best reuse strategy for your app.
Under the Hood
Angular modules are metadata containers that tell the Angular compiler which components, directives, and pipes belong together. When you import a shared module, Angular merges its exported declarations into the importing module's context. This allows components declared in the shared module to be recognized and used in templates of the importing module without redeclaration. Angular's compiler and bundler optimize this merging to avoid duplication in the final app bundle.
Why designed this way?
Angular was designed with NgModules to organize code and manage dependencies clearly. Shared modules were introduced to promote code reuse and reduce duplication. The separation of declarations and exports allows fine control over what is visible outside a module. This design balances encapsulation with reuse, avoiding global pollution while enabling modular apps.
┌───────────────┐      imports      ┌───────────────┐
│ FeatureModule │ ───────────────▶ │ SharedModule  │
│               │                  │ ┌───────────┐ │
│               │                  │ │Component A│ │
│               │                  │ │Directive B│ │
│               │                  │ │Pipe C     │ │
│               │                  │ └───────────┘ │
└───────────────┘                  └───────────────┘

Angular compiler merges exported declarations from SharedModule into FeatureModule's scope.
Myth Busters - 4 Common Misconceptions
Quick: Does importing a shared module automatically provide its services as singletons? Commit to yes or no.
Common Belief:Importing a shared module provides its services as singletons everywhere.
Tap to reveal reality
Reality:Services provided in a shared module are created separately for each module that imports it, causing multiple instances.
Why it matters:This can cause bugs where services do not share state as expected, leading to inconsistent app behavior.
Quick: Can you use a component from a shared module without importing that module? Commit to yes or no.
Common Belief:Once a component is declared in a shared module, it is globally available everywhere.
Tap to reveal reality
Reality:Components must be exported by the shared module and the module must be imported where you want to use them.
Why it matters:Not importing the shared module causes template errors and missing components.
Quick: Does importing a shared module multiple times duplicate its code in the final bundle? Commit to yes or no.
Common Belief:Each import of a shared module duplicates its code in the app bundle, increasing size.
Tap to reveal reality
Reality:Angular merges modules during build, so code is included only once regardless of multiple imports.
Why it matters:This prevents unnecessary bundle size growth and reassures developers about reuse.
Quick: Is it best practice to provide services in shared modules? Commit to yes or no.
Common Belief:Shared modules are the right place to provide services used by many parts of the app.
Tap to reveal reality
Reality:Providing services in shared modules can cause multiple instances; services should be provided in core modules or at root.
Why it matters:Avoiding this prevents subtle bugs and ensures consistent service behavior.
Expert Zone
1
Shared modules should avoid importing heavy modules like FormsModule unless all consumers need them, to keep bundle size minimal.
2
Exporting a module inside a shared module re-exports all its exports, allowing consumers to get multiple features with one import.
3
Standalone components reduce the need for shared modules but combining both can optimize large apps by grouping related reusable pieces.
When NOT to use
Avoid using shared modules to provide singleton services; instead, use a core module or provide services in root. Also, if your app uses standalone components extensively, consider minimizing shared modules to reduce complexity.
Production Patterns
In real apps, shared modules often bundle UI libraries, common form controls, and utility pipes. Teams create multiple shared modules for different domains (e.g., SharedUiModule, SharedUtilsModule) to keep imports focused and maintainable.
Connections
Modular Programming
Shared modules in Angular are a specific example of modular programming principles.
Understanding modular programming helps grasp why grouping reusable code in shared modules improves maintainability and scalability.
Software Design Patterns - DRY Principle
Shared modules implement the DRY (Don't Repeat Yourself) principle by centralizing reusable components.
Knowing DRY helps appreciate how shared modules reduce code duplication and bugs.
Library Management in Package Managers
Shared modules act like local libraries that you import into your app, similar to how package managers handle external libraries.
This connection clarifies how code reuse and dependency management work both inside apps and across projects.
Common Pitfalls
#1Providing services in shared modules causing multiple instances.
Wrong approach:import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DataService } from './data.service'; @NgModule({ declarations: [MyComponent], imports: [CommonModule], exports: [MyComponent], providers: [DataService] // wrong place }) export class SharedModule {}
Correct approach:import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @NgModule({ declarations: [MyComponent], imports: [CommonModule], exports: [MyComponent] }) export class SharedModule {} // Provide DataService in CoreModule or @Injectable({ providedIn: 'root' })
Root cause:Misunderstanding that providers in shared modules create new service instances per import.
#2Not exporting components from shared module causing usage errors.
Wrong approach:import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ButtonComponent } from './button.component'; @NgModule({ declarations: [ButtonComponent], imports: [CommonModule] // missing exports }) export class SharedModule {}
Correct approach:import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ButtonComponent } from './button.component'; @NgModule({ declarations: [ButtonComponent], imports: [CommonModule], exports: [ButtonComponent] }) export class SharedModule {}
Root cause:Forgetting to export components so other modules can use them.
#3Redeclaring shared components in feature modules causing errors.
Wrong approach:import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { ButtonComponent } from '../shared/button.component'; @NgModule({ declarations: [ButtonComponent], // wrong: redeclaration imports: [SharedModule] }) export class FeatureModule {}
Correct approach:import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; @NgModule({ imports: [SharedModule] }) export class FeatureModule {}
Root cause:Confusing declaration with import; components declared once only.
Key Takeaways
Shared modules bundle reusable Angular components, directives, and pipes to avoid code duplication.
You must declare and export components in shared modules, then import the shared module where you want to use them.
Avoid providing services in shared modules to prevent multiple service instances; use core modules or root providers instead.
Angular merges shared modules during build, so importing them multiple times does not duplicate code in the final bundle.
New Angular features like standalone components offer alternatives, but shared modules remain valuable for grouping reusable code.