DefaultPipe
import { ChangeDetectorRef, NgZone, Pipe } from '@angular/core';
@Pipe({name: 'debounce', pure: false})
export class DebouncePipe {
private currentValue: any = null;
private transformValue: any = null;
private timeoutHandle: number = -1;
constructor(
private changeDetector: ChangeDetectorRef,
private zone: NgZone,
) {
}
transform(value: any, debounceTime?: number): any {
if (this.currentValue == null) {
this.currentValue = value;
return value;
}
if (this.currentValue === value) {
clearTimeout(this.timeoutHandle);
return value;
}
if (this.transformValue !== value) {
this.transformValue = value;
clearTimeout(this.timeoutHandle);
this.timeoutHandle = setTimeout(() => {
this.zone.run(() => {
this.currentValue = this.transformValue;
this.transformValue = null;
this.changeDetector.markForCheck();
});
}, typeof debounceTime == 'number' ? debounceTime : 500);
}
return this.currentValue;
}
}