0

I need to pass data from grandparent -> parent -> child component.

This is the grandparent html

<p>
Grant
<app-parent [child]="child" [other]="other"></app-parent>
</p>

Gratnt.ts

other = [{'name': 'abcd', age: 21},{'name': 'pqrs', age: 22}];    
child = [];
    getData() {
    this.service().subscribe((res)=>{
    this.child = res; })

Parent html

<p>
Parent
<app-table [child]="newKid" [other]="newKid2"></app-table>
</p>

parent.ts

@Input child = [];
@Input other = [];
newKid = [];
newKid2 = [];
process() {
//Process Data
this.newKid = this.child;
this.newKid2 = this.other;
}

table.html

<table>
<thead>
<tr *ngFor="let item of child"></tr>
</thead>
<tbody><tr *ngFor="let item of other"></tr></tbody>
</table>

table.ts

@Input child = [];
@Input other = [];

My Question is how to transfer data to nested chain component.?

Rijo
  • 2,963
  • 5
  • 35
  • 62

1 Answers1

1

You can make use of Subjectwhich is available in rxjs

GrandParent.component.html

<app-parent [parentSubject]="parentSubject.asObservable()"></app-parent>

GrandParent.component.ts

@Output() parentSubject: Subject<boolean> = new Subject<boolean>(true);
clickEvent(){
   this.parentSubject.next(true);
}

Parent.Component.html

<app-child [childSubject]="childSubject.asObservable()"></app-child>

Parent.Component.ts

@Input() parentsubject: Subject<boolean> = new Subject<boolean>(true);
@Output() childSubject: Subject<boolean> = new Subject<boolean>(true);

this.parentsubject.subscribe(res=> {
   this.childSubject.next(res);
})

Child.Component.html

<div></div>

Child.Component.ts

@Input() childSubject: Subject<boolean> = new Subject<boolean>();
this.childSubject.subscribe(res => {
  Console.log(res);
});

Hope this helps. Cheers :)

Suhas Parameshwara
  • 1,344
  • 7
  • 15