We all use the ngFor
directive on a daily basis. The directive is used to repeat a template as many times as needed based on an array of data we want to render. We covered how the directive exposes useful local variables in the past.
To help Angular perform DOM updates when items in the array are reordered, new items are added, or existing items are removed, we can add a trackBy
attribute that specifies what unicity criteria Angular will use to track these additions/removals/reorderings:
Of course, this only helps if the array in question is subject to changes in the future. By default, Angular uses Object.is()
to compare values in the array, which is somewhat similar to a ===
comparison.
In our case, we created a function that specifies how to track by _id
:
That way, Angular will know how to compare objects efficiently and won’t perform DOM updates that aren’t needed, which can be a huge performance boost if you’re displaying a massive data table with thousands of records. You can see this example in action on Stackblitz here.