What is the purpose of the variable in ngFor (trackById) [duplicate]

On each ngDoCheck triggered for the ngForOf directive, Angular checks what objects have changed. It uses differs for this process and each differ uses the trackBy function to compare the current object with the new one. The default trackBy function tracks items by identity:

const trackByIdentity = (index: number, item: any) => item;

It receives the current item and should return some value. Then the value returned by the function is compared against the value this function returned the last time. If the value changes, the differ reports a change. So if the default function returns object references, it will not match the current item if the object reference has changed. So you can provide your custom trackBy function that will return something else. For example, some key value of the object. If this key value matches the previous one, then Angular will not detect the change.

The syntax ...trackBy:userByName is no longer supported. You must now provide a function reference. Here is the basic example:

setInterval( () => {
  this.list.length = 0;
  this.list.push({name: 'Gustavo'});
  this.list.push({name: 'Costa'});
}, 2000);

@Component({
  selector: 'my-app',
  template: `
   <li *ngFor="let item of list; trackBy:identify">{{item.name}}</li>
  `
})
export class App {
  list:[];

  identify(index, item){
     return item.name; 
  }

Although the object reference changes, the DOM is not updated. Here is the plunker. If you're curious how ngFor works under the hood, read this answer.


As this topic is still active & finding a clear answer is difficult let me add few examples in addition to @Max's answer:

app.component.ts

array = [
    { "id": 1, "name": "bill" },
    { "id": 2, "name": "bob" },
    { "id": 3, "name": "billy" }
]

foo() {
    this.array = [
        { "id": 1, "name": "foo" },
        { "id": 2, "name": "bob" },
        { "id": 3, "name": "billy" }
    ]
}

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

Let's display the array into 3 divs using *ngFor.

app.component.html

Example of *ngFor without trackBy:

<div *ngFor="let e of array;">
   {{e.id}} - {{e.name}}
</div>
<button (click)="foo()">foo</button>

What happens if we click the foo button ?

→ The 3 divs will be refreshed. Try it yourself, open your console to verify.

Example of *ngFor with trackBy:

<div *ngFor="let e of array; trackBy: identify">
   {{e.id}} - {{e.name}}
</div>
<button (click)="foo()">foo</button>

What happens if we click the foo button ?

→ Only the first div will be refreshed. Try it yourself, open your console to verify.

And what if we updated the first object instead of the whole object ?

foo() {
    this.array[0].name = "foo";
}

→ There is no need to use trackBy here.

It's especially useful when using a Subscription which often looks like what I schematized with array. So it would look like:

 array = [];
 subscription: Subscription;

 ngOnInit(): void {
    this.subscription = this.fooService.getArray().subscribe(data => {
       this.array = data;
    });
 }

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

From the documentation:

To avoid this expensive operation, you can customize the default tracking algorithm. by supplying the trackBy option to NgForOf. trackBy takes a function that has two arguments: index and item. If trackBy is given, Angular tracks changes by the return value of the function.

Read more here: https://angular.io/api/common/NgForOf

Find my original answer here: https://stackoverflow.com/a/57890227/9753985


Here's what I use in my projects to allow tracking by a property of the iterated model without the hassle of writing a function in the component's class :

import { Host, Directive, Input } from "@angular/core";
import { NgForOf } from "@angular/common";

@Directive({
    selector: "[ngForTrackByProperty]"
})
export class TrackByPropertyDirective {

    private _propertyName: string = "";

    public constructor(@Host() private readonly _ngFor: NgForOf<any>) {
        this._ngFor.ngForTrackBy = (_: number, item: any) => this._propertyName ? item[this._propertyName] : item;
    }

    @Input("ngForTrackByProperty")
    public set propertyName(value: string | null) {
        // We must accept null in case the user code omitted the ": 'somePropName'" part.
        this._propertyName = value ?? "";
    }

}

Usage :

<some-tag *ngFor="let item of models; trackByProperty: 'yourDiscriminantProp'">