Shubham Verma
Shubham Verma

Reputation: 9913

TrackBy must be a function, but received undefined In angular 2?

I am creating a demo app in Angular 2. But while doing this, I got this error:

core.umd.js:3491 EXCEPTION: Uncaught (in promise): Error: Error in security.component.html:35:72 caused by: trackBy must be a function, but received undefined. Error: trackBy must be a function, but received undefined

Anyone can suggest me what I am doing wrong in the below code?

security.component.html:

<h2>Template :</h2>
<template ngFor let-hero [ngForOf]="heroes" let-i="index" let-odd="odd" [ngForTrackBy]="trackById">
  <div [class.odd]="odd">({{i}}) {{hero.name}}</div>
</template>

security.component.ts:

import { Component,Input } from '@angular/core';
@Component({
    moduleId    :     module.id,
    selector    :     'security-component',
    templateUrl :     '../views/security.component.html'
})

export class securityComponent{

    private heroes = [
    {id: 11, name: 'Mr. Nice'     },
    {id: 12, name: 'Narco'        },
    {id: 13, name: 'Bombasto'     },
    {id: 14, name: 'Celeritas'    },
    {id: 15, name: 'Magneta'      },
    {id: 16, name: 'RubberMan'    },
    {id: 17, name: 'Dynama'       },
    {id: 18, name: 'Dr IQ'        },
    {id: 19, name: 'Magma'        },
    {id: 20, name: 'Tornado'      }
      ];
}

Upvotes: 3

Views: 2315

Answers (2)

yurzui
yurzui

Reputation: 214007

trackBy takes a function which has two arguments: index and item. If trackBy is given, Angular tracks changes by the return value of the function.

So you need to have function with name trackById in your component

trackById(index, hero) {
  return hero.id    
}

Since 2.4.2 is allowed to use null/undefined values for NgForTrackBy https://github.com/angular/angular/blob/master/CHANGELOG.md#242-2017-01-06

Upvotes: 2

Aluan Haddad
Aluan Haddad

Reputation: 31803

SecurityComponent needs to define trackById

export class SecurityComponent {
  trackById({id}: Hero) {
    return id;
  }
}

Upvotes: 0

Related Questions