0

I have 2 simple components. One is parent the other is child. The parent component has an Array, For each element in the Array, It renders the child component.

parent.component.ts

export class parent implements OnInit {

  data: CustomType[] = [
     {
       id: "child1",
       records: [] // array of string
     },
     {
       id: "child2",
       records: [] // array of string
     }
  ];

  ngOnInit() {}
}

parent.component.html

<section>
  <ChildComponent *ngFor="let child of data | async" [obj]="child"/>
</section>

child.component.ts

export class child implements OnInit {

  // The data is passed from the parent component
  @Input() obj: CustomType;

  ngOnInit() {}
}

child.component.html

<div>
  {{ obj.id }}
</div>

The Problem

The current code works just fine. But the issue is if the records of an element change in the array, It re-renders all the children components. I want to re-render the exact component only.

I am wondering how to use the onPush Change Detection here.

For Example:

If data[0].records changes, It should re-render the data[0]'s child component only.

BadPiggie
  • 5,471
  • 1
  • 14
  • 28
  • 1
    This stack'answer might help you: https://stackoverflow.com/questions/40829951/angular2-ngfor-onpush-change-detection-with-array-mutations – G. Frx Aug 08 '22 at 10:57

1 Answers1

2

add the trackBy function so that it does not render everthing but only renders the one where the trackBy function is changed!

html file

<section>
  <ChildComponent *ngFor="let child of data | async; trackBy: trackBy" [obj]="child"/>
</section>

ts file

  trackBy(index, item) {
    return item.id;
  }

reference here

Naren Murali
  • 19,250
  • 3
  • 27
  • 54
  • I think I need to add `item.records ` instead of `item.id` coz `id` never change. – BadPiggie Aug 08 '22 at 11:00
  • 1
    @BadPiggie You need to add a dummy property called `toggle` set it to true initially, whenever you update records properties, toggle this property, since its under trackby function it will conditionally render it and your issue will be solved without watching records – Naren Murali Aug 08 '22 at 11:04