I want to achieve the next thing, I want to implement 2 components, the first one to contain a table , and the second one to contain some input fields, the trick is the following:
I want that this 2 components to be children components for a parent component. In the parent component I want to have some data. I want the table to be able to listen to data from parent changing, so that it updates realtime, but I also want to be able to interact with the data ( selecting some checkboxes in the table will modify the data in the parent component) And I want the second child component, to get the data from the parent component, populate the input fields with it, and also be able to interact with the data from the parent component by modifying the data in the input fields.
I thought about having a behaviour subject in the parent component, sending it as an input to each of the children components, subscribing to it in both children components, and .next values to the behaviour subject from any of the components.
Would this work? Or is it a better way of achieving it? TL:DR I have 3 components, 2 children components of a main component, I want them to be able to get live updates on some data modified by any of the components and be able to modify the data at any time.
CodePudding user response:
No need for BehaviorSubject
if you only need it in parent and child components. You can simply use two-way data binding using @Input
& @Output
. See this previous answer
CodePudding user response:
Container - Presentation Component Communication
Iptome is right. For container-presentation component communication, it is best to just use inputs. Here's a very basic example:
Container Component Script:
someData$ = of([1, 2, 3])
Container Component Template:
<app-child-one [data]="someData$ | async"></app-child-one>
<app-child-two [data]="someData$ | async"></app-child-two>
Presentation Component Script:
@Input()
data
Here's the above example in a Stackblitz.