Skip to content

Commit 939f4f7

Browse files
committed
feat(cdk): add TrackById and TrackByProp directive
1 parent 2a70edf commit 939f4f7

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

libs/cdk/template/src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
11
export * from './lib/rx-if-list/rx-if-list.directive';
22
export * from './lib/fn/fn.pipe';
3+
4+
export * from './lib/track-by/track-by-id.directive';
5+
export * from './lib/track-by/track-by-prop.directive';
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import {Directive, Host, NgModule} from '@angular/core';
2+
import {CommonModule, NgForOf} from '@angular/common';
3+
4+
@Directive({
5+
// eslint-disable-next-line @angular-eslint/directive-selector
6+
selector: '[ngForTrackById]',
7+
})
8+
export class TrackByIdDirective<T extends {id: unknown}> {
9+
10+
constructor(@Host() private ngFor: NgForOf<T>) {
11+
if (!ngFor){
12+
throw new Error('ngForTrackById must be used with ngFor');
13+
}
14+
this.ngFor.ngForTrackBy = (index: number, item: T) => item.id;
15+
}
16+
}
17+
18+
@NgModule({
19+
imports: [CommonModule],
20+
declarations: [TrackByIdDirective],
21+
exports: [TrackByIdDirective],
22+
})
23+
export class TrackByIdDirectiveModule {}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import {Directive, Host, Input, NgModule} from '@angular/core';
2+
import {CommonModule, NgForOf} from '@angular/common';
3+
4+
@Directive({
5+
// eslint-disable-next-line @angular-eslint/directive-selector
6+
selector: '[ngForTrackByProp]',
7+
})
8+
export class TrackByPropDirective<T> {
9+
@Input() ngForTrackByProp!: keyof T;
10+
11+
constructor(@Host() private ngFor: NgForOf<T>) {
12+
if (!ngFor){
13+
throw new Error('ngForTrackByProp must be used with ngFor');
14+
}
15+
16+
this.ngFor.ngForTrackBy = (index: number, item: T) =>
17+
item[this.ngForTrackByProp];
18+
}
19+
}
20+
21+
@NgModule({
22+
imports: [CommonModule],
23+
declarations: [TrackByPropDirective],
24+
exports: [TrackByPropDirective],
25+
})
26+
export class TrackByPropDirectiveModule {}

0 commit comments

Comments
 (0)