BP159: Use trackBy function in ngFor loops to improve rendering performance

Use trackBy function in ngFor loops to improve rendering performance. The ngFor directive is used to iterate over a collection of data and create a template for each item in the collection. By default, Angular tracks the identity of each item in the collection by its index. However, this can lead to performance issues when the collection is large or when items are added or removed from the collection frequently. To avoid this, you can use the trackBy function to provide a unique identifier for each item in the collection.

The trackBy function takes two arguments: the index of the current item and the item itself. It returns a unique identifier for the item, which Angular uses to track changes to the collection. This allows Angular to only update the DOM for items that have actually changed, rather than re-rendering the entire list every time there is a change. This can significantly improve the performance of your application, especially when dealing with large collections of data.

Here is an example of how to use the trackBy function in an ngFor loop:

// component.ts
items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  { id: 3, name: 'Item 3' }
];

trackByFn(index, item) {
  return item.id;
}

// component.html
<div *ngFor="let item of items; trackBy: trackByFn">
  {{ item.name }}
</div>

In the above example, we have an array of items with unique IDs. We pass the trackByFn function to the ngFor directive using the trackBy input. This function returns the ID of each item, which Angular uses to track changes to the collection. Now, when an item is added, removed, or updated, Angular only updates the DOM for that specific item, rather than re-rendering the entire list.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play