Last active
January 11, 2023 09:23
-
-
Save hakimio/bc2f89910960073523da37abbbb09f5c to your computer and use it in GitHub Desktop.
"ngForTrackByKey" directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <div | |
| *ngFor="let item of items; trackByKey: 'id'" | |
| > | |
| {{item.name}} | |
| </div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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