What is trackBy in ngFor?
Angular's `ngFor` directive is used to iterate over collections and render a template for each item. By default, when the data source for `ngFor` changes (e.g., items are added, removed, or reordered), Angular might re-render the entire DOM elements associated with the changed items. This can lead to performance issues, especially with large lists or complex components.
What is `trackBy`?
trackBy is a function provided to the ngFor directive that helps Angular identify individual items in a list. Instead of treating each item as a new object when the list changes, trackBy tells Angular how to uniquely identify each item.
When trackBy is used, if an item's unique identifier (returned by the trackBy function) has not changed, Angular knows it doesn't need to re-render the associated DOM element, even if other properties of the item object have changed.
Why use `trackBy`?
- Improved Performance: Reduces unnecessary DOM manipulations, leading to faster rendering and a smoother user experience, especially with large dynamic lists.
- Preserves Component State: If list items contain interactive components (e.g., input fields, toggles) that maintain their own internal state,
trackByensures that these components are not destroyed and recreated when the list updates, preserving their state. - Better Animation Experience: When items are reordered, added, or removed, animations can be applied more smoothly because Angular can correctly identify which elements correspond to which data items.
How to use `trackBy`
To use trackBy, you define a function in your component that accepts two arguments: index (the item's index in the array) and item (the item itself). This function should return a unique identifier for the item.
export class MyComponent {
items = [
{ id: 1, name: 'Item A' },
{ id: 2, name: 'Item B' },
{ id: 3, name: 'Item C' }
];
trackByItemId(index: number, item: any): number {
return item.id; // Assuming 'id' is a unique identifier
}
}
Then, you bind this function to the ngFor directive using the trackBy property:
<div *ngFor="let item of items; trackBy: trackByItemId">
{{ item.name }}
</div>
When to use `trackBy`
trackBy is most beneficial when you are dealing with lists that frequently change (items are added, removed, or reordered) and where preserving the DOM elements and their state is important. If your list is static or changes infrequently, the overhead of the trackBy function might not offer significant benefits.