Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Child View not updating

Tags:

angular

My structure is the following:

parent.component.html

<listing-categories #listingCategories [categories]="listingsPaths"></listing-categories>

parent.component.ts

this.listingsPaths = [];
for (let category of listing.categories) {
    // Subscribing to a service and pushing the data to an listingPaths
    this._projectService.getCategories().subscribe((data) => {
     this.listingsPaths.push(data);
    });
}

child.component.ts

@Input() public categories;

child.component.html ...

As you can see I want to send the listingPaths array which is populated in promise, and I want to render it in a child component. I've tried using OnChanges on child component but there weren't any changes triggered when I would push a new object to an array.

I managed to do a 'work around' by creating an Observable and emitting the newly added item to a Child component. How ever I would like to send an array as a whole to a Child component, not emit item by an item.

Here is the solution with Observable:

parent.component.ts

_listingPaths = new Subject<any>();
_listingPathsChanges$ = this._listingPaths.asObservable();

And in for loop, instead of pushing the item to an array, I am emitting it to the child component as:

this._listingsPaths.next(data);

child.component.ts

 this.categories.subscribe((data) => {
     this._categories.push(data); // I don't want this part, I want to receive whole array from a parent
     this.cd.markForCheck();
 })
like image 750
Dino Avatar asked Feb 20 '26 00:02

Dino


1 Answers

Have you set the ChangeDetectionStrategy.OnPush in your child component?? If yes, then you may need to remove it. Any change in the array is not a change in object reference and hence it wont trigger a change detection cycle.

Alternatively, you can create an observable and send the data to child using the async pipe (observable$ | async).

like image 110
Sachin Gupta Avatar answered Feb 22 '26 14:02

Sachin Gupta