0

I am looking at the Angular docs and other various links for communication between Angular child components needing to notify parent components. This could be done for instance via ViewChild, via Output() and EventEmitter or sharing data with a service as suggested here: https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

If a nested child needs to notify a parent and I don't want to use a service I need to chain EventEmitters and repeatedly emit as seen here: Angular 2: How do I emit an event up through multiple nested components?.

But what about instead of using a service or chaining event emitters I just pass an RxJs subject down the component hierarchy through the Input() bindings, do next() in the lowest child and subscribe in the top parent? I haven't seen this suggested but it works and looks pretty simple. My question is, is there any downside to use this pattern for nested child to top parent notification?

user10103655
  • 111
  • 1
  • 11

1 Answers1

1

Main disadvantage of this pattern that your child component became connected to parent. Also someone who will change your component later can do next() at the parent component and this stream became inconsistent. And you have to create this Subject everywhere you use this component instead of using build in Output's mechanism

  • Thanks, right I see the problem with it in terms of exposing the subject at the top level, but I don't see that the coupling is tighter through the Input() than the Output() binding? – user10103655 Nov 15 '19 at 11:35
  • It's broke separation of components. For example in the child component you can put something another in property which refers to Subject. So for main reason to avoid this way is it broke components pattern, because child component can directly change parent and it can be unclear. hard to debug – Kasabucki Alexandr Nov 15 '19 at 11:43
  • It would be adviseable to separate these events from the components all together and just have a service handle this so in case any other component in your system would like to know what is going they can. This whole approach is basically similar to ngrx and CQRS which you should check out in general – misha130 Nov 15 '19 at 12:30