Angular data communication to and from components

324 Views Asked by At

I have a parent component (P1) and two child components(C1 and C2). Both the child components have a primeng data-table which are editable. I have two buttons on P1 : fetch() and save(). fetch() calls the database to get the data. I'm using a shared service to fetch data and pass it down to the components using BehaviorSubject. My data object looks like:

export interface ParentObj { name: string; child1 : Child1[]; child2: Child2[]}
export interface Child1 { weight: number;}
export interface Child2 { code: string;}

Child components subscribe to the data from the shared service. Now the issue is that the Child components also modify the data which they have. So on click of save() on the P1, I am unable to get the latest modified values from the child components as I do not have any way of notifying P1 that C1 and/or C2 has changed the data.

Is there a way to accomplish the same so that I could notify the child components when the save() is called and it reflects in the ParentObj?.

2

There are 2 best solutions below

0
On BEST ANSWER

I was able to solve it using the ViewChild from '@angular/core' as there was no event trigger on the child components. The parent can read the child attributes using the @ViewChild(ChildComponent) child; Reference: Here

0
On

You can use event emitter for this purpose AND this is most useful when communicating from child component to parent component.

Example:-

P1 component:-

<c1 (notifyParent)="notify(data)"></c1>
<c2 (notifyParent)="notify(data)"></c1>

notify(data) {
    console.log(data); //notify parent
}

C1 component:-

@Output() notifyParent= new EventEmitter();

and then

this.notifyParent.emit(data) //or notify with true value

C2 component:-

@Output() notifyParent= new EventEmitter();

and then

this.notifParent.emit(data) //or notify with true value