interface
A function optionally passed into the NgForOf directive to customize how NgForOf uniquely identifies items in an iterable.
interface TrackByFunction<T> {
<U extends T>(index: number, item: T & U): any
} NgForOf needs to uniquely identify items in the iterable to correctly perform DOM updates when items in the iterable are reordered, new items are added, or existing items are removed.
In all of these scenarios it is usually desirable to only update the DOM elements associated with the items affected by the change. This behavior is important to:
<select> element when nested <option> elements are dynamically populated using NgForOf and the bound iterable is updatedA common use for custom trackBy functions is when the model that NgForOf iterates over contains a property with a unique identifier. For example, given a model:
class User {
id: number;
name: string;
...
} a custom trackBy function could look like the following:
function userTrackBy(index, user) {
return user.id;
} A custom trackBy function must have several properties:
| call signature | ||||||
|---|---|---|---|---|---|---|
|
index | number | The index of the item within the iterable. |
item | T & U | The item in the iterable. |
any
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/core/TrackByFunction