Skip to content

Instantly share code, notes, and snippets.

@vilicvane
Created September 27, 2017 09:48
Show Gist options
  • Save vilicvane/1f5e9ae082bd3dd83bcc9c8a4d3e19a1 to your computer and use it in GitHub Desktop.
Save vilicvane/1f5e9ae082bd3dd83bcc9c8a4d3e19a1 to your computer and use it in GitHub Desktop.
Angular: "track by" structural directive for single component/element
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