0

I have two main components - list and detail. In the third component, which doesn't have a parent/child relationship with either of the first two components, I need to know which component is currently being used/displayed and based on that, perform some actions in it.

Right now, I'm subscribed to URL parameters within each of the two components (list and detail). Within the two subscriptions I'm setting a behaviour subject (using next) to which the third component is subscribed. I set the behaviour subject to 'list' within the subscription to URL parameters within list component and I set the behaviour subject to 'detail' within the subscrription to URL parameters within detail component. That is how the third component always knows which component is being displayed.

I'm sure there is a a better way than to play this kind of ping-pong?

Mandy
  • 107
  • 1
  • 2
  • 9

2 Answers2

1

To me your approach seems correct. I made a Stackblitz example of how I would probably handle it: https://stackblitz.com/edit/angular-5mfjbz

In the example Parent = List and Child = Detail and the Third component observes what's happening in the other components.

Kari F.
  • 1,214
  • 10
  • 16
1

As per Angular documentation, there is only one way to achieve non related component interaction, shared services.

From you question, I don't think you need explanation on how to achieve shared services. This is the only way to achieve communication between components which does not have parent child relationship.

Also, shared services solution is easy to implement, rather than using store like ngrx

You can always use store ngrx, and try to set and get values wherever required.

Plochie
  • 3,944
  • 1
  • 17
  • 33
  • Thank you, I haven't used ngrx so far (and like you, think it's unnecessary for this problem), but it can come handy one day, so thank you for reminding me of it! – Mandy Dec 13 '19 at 16:12