Home > Back-end >  Refresh specific child into ngFor
Refresh specific child into ngFor

Time:07-27

For performance issues i'm trying to make only childrens that has changed reload. I have this array of objects

public table: any[] = [
    {id:1, data:"data1"},
    {id:2, data:"data2"},
    {id:3, data:"data3"},
    {id:4, data:"data4"},
  ]

Which is rendered like this:

<app-cell *ngFor="let cell of table" [cellData]="cell"></app-cell>

Once i modify a element, for example the one with "id:2" :

change() {
    this.table[2].data = 'Data3 but has changed';
  }

All the child components in ngFor loop are reloaded. I have tried to use trackBy but my knowledges are not sufficent to achieve what I'm trying to do.

How can I only make the ones who changed reload ?

Thanks in advance,

Nicolas.

CodePudding user response:

You should keep trying to use the trackBy function. My suggestion is to combine both id and data in a string and return that:

trackByIdAndData(index: number, item: any): string {
  return `${item?.id}_${item?.data}`;
}

And apply this track by function to your ngFor:

<app-cell *ngFor="let cell of table; trackBy: trackByIdAndData" [cellData]="cell"></app-cell>
  • Related