Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and How Should I Use trackBy in Angular's ngFor Directive for Optimal Performance?

I'm seeking clarification on the usage of the trackBy function with Angular's ngFor directive to enhance performance. While I understand the basics of ngFor and its iteration over arrays to generate templates, I'm uncertain about the specific scenarios and methodologies where trackBy should be employed.

Here's what I've attempted:

I've read the Angular documentation on trackBy, but I'm still unclear about its practical application. I've experimented with ngFor loops in my Angular projects, but I'm uncertain about the necessity and proper implementation of trackBy.

I'm expecting a clear explanation of when and why it's beneficial to use trackBy in ngFor loops. I'd like to understand any potential performance improvements or pitfalls associated with using or not using trackBy. Examples or demonstrations illustrating effective usage of trackBy within ngFor loops would be highly beneficial. Any guidance or insights on this matter would be greatly appreciated. Thank you!

like image 724
Chetali Polekar Avatar asked Oct 30 '25 09:10

Chetali Polekar


1 Answers

ngFor loops through array and generates a repeating template.

When something gets changed in the data object used to make the template, ngFor has two options.

  1. Rerender the entire repeated elements
  2. Rerender only the element, where the change occurred.

SO lets look at an example

array1 = [{test:1},{test:1}{test:1},{test:1}]; // this array is used for ngFor
    
    
//next an api call updates array1 //emulates an API call 
of([{test:1},{test:1}{test:1},{test:1}]).subscribe(() => {
    this.array1 = [{test:1},{test:1}{test:1},{test:1}];
});

So when you look at from ngFor perspective, it received an input array at the beginning, as you know javascript arrays are stored as references read more some reference to the location of the array in the memory.

When the API call is made, a new array is assigned to array1, but from the perspective of ngFor a new reference will be incoming, so naturally ngFor has to rerender the entire array because it does not know what changed inside the array.

When you specify ngFor with trackBy you specify the key with which to track the identify of the elements of the array, here is the id changes, we know something has happened to the elements and differs function of angular will catch the change and rerender.

For a more detailed look, try exploring the source code

like image 134
Naren Murali Avatar answered Nov 01 '25 06:11

Naren Murali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!