Use ngFor with trackBy to improve performance in Angular applications
In this article we are going to see how we can improve performance of angular application using ngFor
with trackBy
function.
ngFor Directive
We mostly use ngFor
directive in our angular application to render template for each item in collection. ngFor
creates a copy of template with current item’s data and paints it to DOM.
In Applications, we do add, update and delete operations that changes our collection. So whenever any operation is performed, we request fresh data from backend API and replace our existing collection with new collection.
When new data arrives, ngFor
under the hood removes all items from DOM and creates them again with updated data because ngFor
is un-informed about data and don't know which items in collection were added/updated or deleted.
Animation of DOM manipulation done by ngFor
upon new data arrival is given below.
ngFor directive with trackBy
The trackBy
is a function that takes index and current item as arguments and should return unique identifier of item like id or uuid.
by using trackBy
function, we guide ngFor
to take informed decisions upon new data arrival rather than removing all DOM nodes and creating them again.
When new data arrives, ngFor
looks for data changes using trackBy
function and only add, update, delete changed data items.
Animation of DOM manipulation done by ngFor
with trackBy
upon new data arrival is given below.
Conclusion
DOM manipulations are costly operations and must be minimized.
If we have large collection of items or complex template like card with multiple elements, rendering will take significant time as ngFor
will remove all elements from DOM and re-create them with fresh data.
In contrast, with trackBy
function less DOM manipulations will be done because ngFor
will only add new elements, remove deleted elements and update modified elements.
you can find demo code here.
Thank you for reading my article. Please let me know if you liked and understood this article, and how I could improve it.