Reputation: 345
Is it correct to use services to communicate between angular components?
If I have a component which opens a modal
this.taskService.activeTask = this.currentTask;
this.tagSelectModalRef = this.modalService.show(TagSelectorComponent, {});
Is it correct to "pass" the element that the modal has to work with via a service as in the example?
If it were to components that visualize side by side where the click in one of them affect the other component, will it also be correct?
Thanks,
Enric
Upvotes: 0
Views: 1590
Reputation: 668
You need to use services to communicate between sibling components. If you need to communicate parent with children or children with parent use @input and @output
Upvotes: 0
Reputation: 147
I have personally done what you are trying to do in the past by creating 2 separate components. I find that this is a cleaner implementation assuming all you're doing in that service is sharing data. But technically there is nothing wrong with using a service if you do want to go that route. If you were doing operations on that data that were independent of both the modal and the component and were looking to run them separately and independent of the component or modal I would lean more towards using a service.
Concept of using 2 components explained below:
So you'll have your component you already have, but convert the modal into your second component.
Anything that needs to be shared between the two components can then be done by using @Input
, @ViewChild
, and @Output
. Basically, anything you need passed down from your top level component you would use an @Input
in the modal component. Anything you need to notify the top level component of from the modal, depending on what you're trying to pass back up the tree or what behaviors you’re looking to trigger you could use either an @Output
and an EventEmitter
from the @angular/core
imports in the modal component, or you could use @ViewChild
in the top level component.
Upvotes: 2
Reputation: 6983
Yes you can use a service to communicate between components. It's clearly documented in the official angular documentaion in the component interaction section.
Upvotes: 3