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!
ngFor loops through array and generates a repeating template.
When something gets changed in the data object used to make the template,
ngForhas two options.SO lets look at an example
So when you look at from
ngForperspective, 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 ofngFora new reference will be incoming, so naturallyngForhas to rerender the entire array because it does not know what changed inside the array.When you specify
ngForwithtrackByyou 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 anddiffersfunction of angular will catch the change and rerender.For a more detailed look, try exploring the
source code