Creating a shared module in Angular is an excellent way to organize your code and encourage reusability across your application. A shared module consists of declarations (components, directives, and pipes) and providers (services) that multiple feature modules in your application may need.
Here are the step-by-step instructions to create and use a shared module:
1. Create a shared module:
Create a new folder named "shared" inside the "app" directory (or anywhere you prefer). Then, generate the SharedModule using Angular CLI, as shown below:
ng generate module shared/shared
This command will create ‘shared.module.ts‘ inside the "shared" folder.
2. Add declarations and exports:
Declare components, directives, and pipes that will be shared, and export them so that other modules can use them. You can create these items in the "shared" folder and add them to the ‘@NgModule‘ decorator of the ‘shared.module.ts‘ file. Here’s an example:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
@NgModule({
declarations: [
HeaderComponent,
FooterComponent
],
imports: [
CommonModule
],
exports: [
HeaderComponent,
FooterComponent
]
})
export class SharedModule { }
In this example, HeaderComponent and FooterComponent will be available for other modules to use.
3. Import ‘SharedModule‘ in feature modules:
Import the ‘SharedModule‘ in any feature module where you want to use the shared components, directives, or pipes. Remember to add the ‘SharedModule‘ to the ‘imports‘ array in the ‘@NgModule‘ decorator.
For example, let’s import the ‘SharedModule‘ into a feature module called ‘UserModule‘:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';
import { UserComponent } from './user/user.component';
@NgModule({
declarations: [
UserComponent
],
imports: [
CommonModule,
SharedModule
]
})
export class UserModule { }
Now the ‘UserComponent‘ in the ‘UserModule‘ can use the shared components (like HeaderComponent and FooterComponent) as if they were part of its own module.
That’s it! You’ve successfully created and used a shared module in Angular. Using shared modules helps keep your code organized and promotes reusability, making your application more maintainable in the long run.