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.
Advertisement
Answer
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