How trackBy Improves Performance in Angular?
September 21, 2024 8:45 PM
The trackBy
function in Angular improves performance and minimizes DOM manipulations by providing a way for Angular to uniquely identify each item in a list. This allows Angular to efficiently update only the items that have changed, rather than re-rendering the entire list. Here's how it works:
How trackBy
Improves Performance
Unique Identification: By using a unique identifier for each item, Angular can keep track of which items have been added, removed, or moved. This is done through the
trackBy
function, which returns a unique key for each item.Efficient DOM Updates: When the list changes, Angular uses the unique keys to determine which items need to be updated. Instead of re-rendering the entire list, Angular only updates the specific items that have changed. This reduces the number of DOM manipulations, which can be expensive in terms of performance.
State Preservation: If the list items contain stateful elements (like form inputs), using a unique key ensures that the state is preserved correctly when the list is updated. Without
trackBy
, Angular might recreate the entire list, losing the state of each item.
In example, we have two ways of rendering the list
Using @for
with track
<ul>
@for (ingredient of ingredientList; track ingredient.name) {
<li>{{ingredient.name}} {{ingredient.quantity}}</li>
}
</ul>
Using *ngFor
with trackBy
:
<ul>
<li *ngFor="letingredient of ingredientList; indexasi; trackBy: trackByFn">
{{ingredient.name}} {{ingredient.quantity}}
</li>
</ul>
trackBy
Function
How It Works?
- Initial Render: When the list is first rendered, Angular creates DOM elements for each item in the list.
- List Update: If the list changes (e.g., an item is added, removed, or reordered), Angular uses the
trackBy
function to determine which items have changed. - Efficient Update: Angular updates only the DOM elements that correspond to the changed items, rather than re-rendering the entire list. This minimizes the number of DOM manipulations and improves performance.
Summary
- Without
trackBy
: Angular re-renders the entire list whenever it changes, leading to more DOM manipulations and potential performance issues. - With
trackBy
: Angular uses the unique keys to update only the changed items, reducing the number of DOM manipulations and improving performance.
By using the trackBy
function, you ensure that Angular handles dynamic lists efficiently, preserving the state of each item and minimizing unnecessary DOM updates.
Comments