question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Supporting trackBy:<expression|id>

See original GitHub issue

I’m submitting a … (check one with “x”)

[ ] bug report => search github for a similar issue or PR before submitting
[X] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
  • Angular version: 2.1.2

What is the motivation / use case for changing the behavior? Related to the discussion here http://stackoverflow.com/questions/36322829/how-to-use-track-by-inside-ngfor-angular-2, I’d like to propose supporting just stating a property name (alternatively inline function) for trackBy. The use case is that ngFor and trackBy are very common , and the current requirement of having to specify a function is confusing, terse, and arguably worse than Angular 1. Thus, I’d wish something like this to work

<li *ngFor="let item of items; trackBy:'id'">
  {{item.whatever}}
</li>

and/or

<li *ngFor="let item of items; trackBy:item.id">
  {{item.whatever}}
</li>

Issue Analytics

  • State:open
  • Created 7 years ago
  • Reactions:76
  • Comments:16 (6 by maintainers)

github_iconTop GitHub Comments

9reactions
alberto-chiesacommented, Dec 3, 2019

I don’t get why this should be so complicated. Really, guys, KIS. We just need to extend the ngForTrackBy signature to be less pedantic:

  private _trackByIndex(index: number, _value: any) {
    return index;
  }

  private _trackByPropertyFactory<T>(propName: keyof<T>): TrackByFunction<T> {
    return (_index: number, value: any) => value != null ? value[propName] : _index;
  }

  @Input()
  set ngForTrackBy(fn: TrackByFunction<T> | '$index'  | keyof<T>) {
    if (fn === '$index') fn = this._trackByIndex;
    if (typeof fn === 'string') fn = this._trackByPropertyFactory(fn);

    if (isDevMode() && fn != null && typeof fn !== 'function') {
      // TODO(vicb): use a log service once there is a public one available
      if (<any>console && <any>console.warn) {
        console.warn(
            `trackBy must be a function, but received ${JSON.stringify(fn)}. ` +
            `See https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html#!#change-propagation for more information.`);
      }
    }
    this._trackByFn = fn;
  }

  // changes also this signature, just to keep the TS compiler happy
  get ngForTrackBy(): TrackByFunction<T>  | '$index'  | keyof<T> { return this._trackByFn; }

Done. No fancy compiler stuff needed. And it’s type safe because of keyof.

trackBy: '$index' or trackBy: 'propName' seem to be simple enough to grasp.

8reactions
nigrosimonecommented, Mar 7, 2022

Disclaimer! I’m the author of NgForTrackByProperty

Angular global trackBy directive by passing a property name for track the ngFor item with strict type checking.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <ul>
      <li *ngFor="let item of list; trackByProperty: 'id'">{{ item.id }} {{ item.name }}</li>
    </ul>
  `,
})
export class AppComponent {
  list = [
    { id: 0, name: 'foo' },
    { id: 1, name: 'bar' },
    { id: 2, name: 'baz' },
  ];
}

Online demo

Source code

Read more comments on GitHub >

github_iconTop Results From Across the Web

Support for Track-It! - BMC Software
Get support for Track-It!, including documentation, frequently asked questions, knowledge articles, downloads, training, and more.
Read more >
On Track Support Services
You can focus on driving and leave the rest to us – we provide complete track support for both car and driver. From...
Read more >
What to expect from Toggl Track Support?
Toggl Track Support can be reached via the support@track.toggl.com email address, the Contact page, or by using feedback forms available in various Toggl ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found