Created
September 27, 2017 09:48
-
-
Save vilicvane/1f5e9ae082bd3dd83bcc9c8a4d3e19a1 to your computer and use it in GitHub Desktop.
Angular: "track by" structural directive for single component/element
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, | |
EmbeddedViewRef, | |
Input, | |
OnInit, | |
TemplateRef, | |
ViewContainerRef, | |
} from '@angular/core'; | |
import { BehaviorSubject } from 'rxjs/BehaviorSubject'; | |
@Directive({ | |
selector: '[mfTrackBy]', | |
}) | |
export class TrackByDirective implements OnInit { | |
private value$ = new BehaviorSubject<any>(undefined); | |
private viewRef: EmbeddedViewRef<any> | undefined; | |
constructor( | |
private viewContainer: ViewContainerRef, | |
private templateRef: TemplateRef<any>, | |
) { } | |
@Input() | |
set mfTrackBy(value: any) { | |
this.value$.next(value); | |
} | |
ngOnInit(): void { | |
this.value$ | |
.distinctUntilChanged() | |
.subscribe(() => { | |
if (this.viewRef) { | |
this.viewContainer.clear(); | |
} | |
this.viewRef = this.viewContainer.createEmbeddedView(this.templateRef); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment