Search code examples
angularngforangularjs-track-by

ngFor trackBy function with custom parameters


The trackBy function (e.g. in an ngFor) provides two arguments: index and item (from the collection being iterated over). Is there a way to pass additional information (as parameters?) to th trackBy function?

My case is that I might be iterating over a variety of types for each instance of my component (which contains the ngFor), with different identifying field names. Ideally, I'd like to be able to pass a third parameter indicating which field in my item should be read.


Solution

  • bind method can help you to do this trick

    template.html

    <div *ngFor="let item of items; trackBy: trackByFn.bind(this, 'name')">
      {{ item }}
    </div>
    

    component.ts

    items = [
      {
        id: 1,
        name: 'name1'
      },
      {
        id: 2,
        name: 'name2'
      }
    ]
    trackByFn(customParam, index, item) {
      return item[customParam];
    }