Reputation: 2023
So I have two components, CompA and compA5 which are 3 or 4 levels apart, I want to create a communication channel between the components.
Lets say from component CompA i want to send event to compA5 to return some data, wait for it to return data and than take some action. Is it possible to create a service or any other best practices to achieve this kind of behavior.
Upvotes: 1
Views: 350
Reputation: 3179
There is nothing better than the original Angular.io documentation example Parent and children communicate via a service.
Upvotes: 0
Reputation: 39462
The best practice for Component Communication where two components are either siblings or are not realted to each other is to create a shared service.
This shared service will have a Subject
/BehaviorSubject
variable. Since this is a shared service, both the components will inject it as a dependency.
Now one can change the value of this Subject
/BehaviorSubject
by calling next
on it and passing it the data it wants the other component to get.
The other component will be subscribe
-ing to this Subject
/BehaviorSubject
and will get the data automatically.
Here's the StackBlitz Link for a simple demo.
Upvotes: 2