Dino
Dino

Reputation: 1347

Angular ngrx manage observables and subscriptions between parent and children

My store State has a slice of data called selected variables:

enter image description here

If I only had one component, I'd subscribe to an observable and consume the content like follows:

enter image description here

I designed a parent component that contains three tabs with three children components to make my html and typescript code cleaner:

enter image description here

Any of the children components, as well as the parent component, can change the selectedVariable portion of the State. Is it necessary to pick and subscribe to the'selectedVariable' in each child and parent component to make the children and parent react to any state change, or is there a more efficient and elegant way to accomplish the same result?

Upvotes: 1

Views: 737

Answers (1)

Armen Vardanyan
Armen Vardanyan

Reputation: 3315

A better way to do this is to use the async pipe and pass the data as an Input to the three child components. There you can use that data either directly in the template, or use ngOnChanges to react to the changes in that store data in an imperative way. If you want to dispatch actions from child components, you can inject the Store into those components and dispatch from them, or (a more preferable approach, in my opinion) emit events from child components (using Output EventEmitters) and dispatch only from the parent component. This way you will decouple the components from the store, and only your parent component will handle the store logic, while the child components handle displaying UI.

Upvotes: 1

Related Questions