cft

Improving Angular Application Performance - using TrackBy

In this post, I will talk about how can you can improve the performance of the Angular application using trackBy in which you are using ngFor directive for displaying data and upon some user action we need to change some part of the data.


user

Nikhil Dhawan

2 years ago | 1 min read

Hi all, in this post, I will talk about how can you can improve the performance of the Angular application using trackBy in which you are using ngFor directive for displaying data and upon some user action we need to change some part of data.

When we just use ngFor directive where we need to change data it will cause the complete list to rerender and might affect application performance. So at that time, we should use trackBy implementation to make angular aware which among the data is old and which is the new addition.

We will see this with an example, full demo code can be referred to at GitHub and Stackblitz.

I this demo we have a list that we show via ngFor and a button with which we will add another item to the list.

And corresponding code is


so now if you open the chrome developer tool and focus on list items while clicking on Add button you will see, the whole list is rerendered on the screen(which can be seen when in dev tools we see highlighted rows that get rerendered as in the below image)

Now let us implement the trackBy function for this and see the difference.

The HTML code will changes will be

and the code for this function in typescript will be

So if you see here we are returning id in the trackBy function, which is something unique to the object in the array which helps Angular understand the uniqueness of each object in our case.

If you now relaunch the application and do the same activity you will be able to see that only a new object line is added without rerendering the old objects.

Hope you were able to understand the concept of using trackBy and how it can help improve performance.

If you liked it please share it with your friends or if any suggestions reach me out on Twitter or comment below.

Till next time Happy Learning!


Upvote


user
Created by

Nikhil Dhawan

I am a Technology Enthusiast , always ready to explore something new


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles