Multiple *ngFor trackBy functions in the same component

122 Views Asked by At

I added some trackBy functions on *ngFor directives of an Angular project in order to boost performances.
There is one component with 2 lists of items. The trackBy function is the same for both lists and return the item's id to identify it. However, some of the items in one list could have the same id of items in the second one.

I wonder if it could lead to a problem of uniqueness in Angular's change detection with the trackBy and might create side effects ?
I'm looking for a way to test it or if someone already knows if it would be the case and can explain. Because I haven't seen any post/documentation that mention such case and I am pretty sure this happens a lot in applications.

A side effect I assume:
if one list1 item is updated and it has a common id with another item in list2, does this second item refresh as well because of an Angular "confusion" in the change detection ?

component.html
<ng-container *ngFor="let item of list1; trackBy: trackById">
             ...                               
</ng-container>
<ng-container *ngFor="let item of list2; trackBy: trackById">
             ...                               
</ng-container>
component.ts
list1 = [{ id: 1 }, { id: 3 }, { id: 5 }];
list2 = [{ id: 1 }, { id: 4 }, { id: 5 }, { id: 7 }];

trackById<T extends { id: string }>(item: T): string {
   return item.id;
}
1

There are 1 best solutions below

0
On BEST ANSWER

After some more researches and tests: Angular trackBy function has its own local scope and is not affected by the rest of the DOM / other trackBy functions.
So it does not matter if some items have the same ids in different trackBy functions inside the same component