What is the purpose of ngFor trackBy?

The main purpose of using *ngFor with trackBy option is performance optimization. Normally if you use NgFor with large data sets, a small change to one item by removing or adding an item, can trigger a cascade of DOM manipulations. In this case, Angular sees only a fresh list of new object references and to replace the old DOM elements with all new DOM elements. You can help Angular to track which items added or removed by providing a trackBy function which takes the index and the current item as arguments and needs to return the unique identifier for this item.

For example, lets set trackBy to the trackByTodos() method

<div *ngFor="let todo of todos; trackBy: trackByTodos">
({{todo.id}}) {{todo.name}}
</div>

and define the trackByTodos method,

trackByTodos(index: number, item: Todo): number { return todo.id; }

Author of content
Edit this page

Made by Michael Sakhniuk

Twitter