Skip to content

Instantly share code, notes, and snippets.

@hakimio
Last active January 11, 2023 09:23
Show Gist options
  • Select an option

  • Save hakimio/bc2f89910960073523da37abbbb09f5c to your computer and use it in GitHub Desktop.

Select an option

Save hakimio/bc2f89910960073523da37abbbb09f5c to your computer and use it in GitHub Desktop.
"ngForTrackByKey" directive
<div
*ngFor="let item of items; trackByKey: 'id'"
>
{{item.name}}
</div>
import {Directive, Host, Input} from '@angular/core';
import {NgForOf} from '@angular/common';
@Directive({
selector: '[ngForTrackByKey]',
standalone: true
})
export class TrackByKeyDirective<T> {
@Input('ngForTrackByKey')
key: string;
constructor(
@Host()
private ngFor: NgForOf<T>
) {
this.ngFor.ngForTrackBy = (index: number, item: T) => item[this.key];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment