I am new to Angular and just started learning. I have a situation where I like to use the same component across multiple projects.
Let's say, I have a CustomerComponent
and it does CRUD operations.
Now I want to use the CustomerComponent
in project A and project B. The reason is that if I have to modify the CustomerComponent
, I can modify only in one place instead of multiple projects.
Is it possible to create a component like that?
If it is possible, please guide me how I can accomplish this one.
Thanks in advance.
Yes. This is definitely possible. You should do that by creating a separate module that will have this component registered on it. Then you can export this component from this module and import the module into the app modules of the projects in which you want to use this component.
Say, for example, you have a core module, something like this:
@NgModule({
declarations: [CustomerComponent],
exports: [CustomerComponent],
})
export class CoreModule{}
In here we have declared a component named CustomerComponent
and we have also exported it from this CoreModule
So now, if say, you have two different projects with AppModule as their root modules, in both these projects, you'll have to import this CoreModule
. Something like this:
@NgModule({
imports: [CoreModule],
})
export class AppModule{}
And once this is done, the CoreModule would be registered as a Module, exported features of which can then be used inside your AppModule.
Definitely, that it is actually encouraged to share Components via Modules:
See more here: https://angular.io/guide/sharing-ngmodules
Additionally, if you want to share services around since they are implemented as Singletons it's a bit different.
Edit (Dec 12, 18) Here is a link talking about singleton services: https://angular.io/guide/singleton-services
Use case matters however for clarity you can read above. Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With