Shared Module in Angular
Intro:
We intend to build an angular application with shared module for making use of reusable codes.
Problem:
Since the time an application is built, the app becomes bigger gradually and this causes different kind of problems. For example, reusable classes are seen in different parts of the app. It is not a good method because, in long-term, it can result in bad performance and dirty code.
So you have to fix it :)
Solution:
All reusable classes such as components, directives, pipes, etc. can be put in a module so that the module can be imported simply in every other module whenever necessary instead of having to import multiple classes all over the app.
Step 1:
Let’s get started and build an angular app with a few commands.
// install angular cli
npm i @angular/cli// build a sharedModule-app
ng new sharedModule-app// locate sharedModule-app directory
cd sharedModule-app// serve the app
ng serve
Now we have our app called sharedModule-app available at http://localhost:4200.
Step 2:
In app directory we create two modules; main module and shared module with these commands:
ng generate module main
ng g m shared
The second line is the short version of the first line.
In main module we generate home component so that we can use a lot of reusable code in it.
ng g c home
Now we are going to generate a pipe and a component in the shared module so that we can use it in home component without importing those individually.
First of all, we should locate shared directory and run these commands:
ng g c welcome
ng g p filter
Tada! It’s like magic! isn’t it? :)
In welcom.component.html write a message:
<h4>Welcome message works!</h4>
And in filter.pipe.ts write a simple switch case code:
Step 3:
We have to note that if we want to use this component and pipe in home component which exists in main module, we have to import the shared module into the main module and we have to export the component and the pipe in the shared module.
shared.module.ts looks like this:
And main.module.ts:
Step 4:
In home.component.html we use the welcome component and filter pipe like this:
Now we have this result in home component:
See the complete code in my github repository: https://github.com/mobinakhalilzade/sharedModule-app