Optimize your Angular app with trackBy
First, let’s understand why trackBy
is important. When you use the ngFor
directive to render a list of items, Angular uses the identity of each item to track changes in the list. By default, Angular uses object references to identify items. That means if you have a list of objects and you modify an object in the list, Angular will re-render the entire list, even if only one object has changed.
This can be a problem if you have a large list, as re-rendering the entire list can be expensive in terms of performance. That’s where trackBy
comes in. It allows you to provide a custom tracking function that Angular uses to identify items in the list. If an item's identifier has not changed, Angular knows that the item has not changed, and it doesn't need to re-render it.
Here’s an example of how to use trackBy
:
<ul>
<li *ngFor="let item of items; trackBy: trackByFn">{{item.name}}</li>
</ul>
In this example, items
is an array of objects with a name
property. We're using the ngFor
directive to render a list of <li>
elements, one for each item in the array. We've also added the trackBy
directive, which tells Angular to use a custom tracking function called trackByFn
.
Here’s what the trackByFn
function might look like:
trackByFn(index: number, item: any): number {
return item.id;
}
In this example, we’re returning the id
property of each item as the identifier. Assuming that each item in the list has a unique id
, this will allow Angular to track changes in the list more efficiently. If an items id
has not changed, Angular will know that the item has not changed, and it won't re-render it.
It’s worth noting that the trackByFn
function must return a unique identifier for each item in the list. If two items in the list have the same identifier, Angular will assume that they are the same item and won't be able to distinguish between them. This can cause rendering errors or performance issues.
In summary, using trackBy
can significantly improve the performance of your Angular app when rendering large lists of data. By providing a custom tracking function, you can help Angular identify which items in the list have changed and need to be re-rendered.
Thanks for reading!
I hope you found this article useful. If you have any questions or suggestions, please leave comments. Your feedback helps me to become better.
Don’t forget to subscribe⭐️
Facebook Page: https://www.facebook.com/designTechWorld1
Instagram Page: https://www.instagram.com/techd.esign/
Youtube Channel: https://www.youtube.com/@tech..Design/
Twitter: https://twitter.com/sumit_singh2311
Gear used:
Laptop: https://amzn.to/3yKkzaC
You can prefer React Book: https://amzn.to/3Tw29nx
Some extra books related to programing language:
*Important Disclaimer — “Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”