Search code examples
angulartypescriptangular-servicesangular-componentsangular4-router

Angular Extends Component Interaction


My partner and I are developing an Angular 4 application where the highest level component (AppComponent) has a component (we'll call UndoComponent) that persists throughout the application. We have a router-outlet in AppComponent and for this example let's say the Router is currently displaying ContentComponent.

There are times where an item in ContentComponent may need to talk to the UndoComponent. For instance, when a certain event is fired we may want to push some information onto a stack inside of UndoComponent. So we would need to do something to get ContentComponent to tell AppComponent to update UndoComponent's stack.

I know that updating a parent from child (particularly, a routed child component) can be achieved by using a shared service and Observables, but my partner suggested that we make ContentComponent extend AppComponent and then use a method inside AppComponent to update the UndoComponent.

I feel uneasy about this solution. I can't find any information about why you should or should not use component inheritance for parent/child communications. I do feel like it would be much easier to do it this way so we wouldn't have to keep creating observables in our service to make these types of updates happen.

Thoughts?


Solution

  • I'd just use a service and Observables, and most developers I think would agree. I don't see the benefit of even trying a different approach, especially for a singular situation. The docs even outline using a service for inter-component communications. Also, with a service any updates won't require re-evaluating the solution. For example, right now you have a single router-outlet that loads a routed component, but what if you change it to be instead a routed component with child routes. How would that filter back up to update the UndoComponent. If you have a service you would just continue to inject the service and it still works with no effort regardless of how deep your router-outlets go, or any other changes you might not foresee.