Created
February 10, 2019 21:10
-
-
Save Bengejd/eb8b361e233e1845b06ec0ce07d63b70 to your computer and use it in GitHub Desktop.
Debounce a user input
This file contains 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
@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) { | |
// there is no value that needs debouncing at this point | |
clearTimeout(this.timeoutHandle); | |
return value; | |
} | |
if (this.transformValue !== value) { | |
// there is a new value that needs to be debounced | |
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; | |
} | |
} |
This file contains 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 | |
*ngIf="hasInputError(contentOption) | debounce" | |
class="error-message"> | |
{{errorMessage(contentOption)}} | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment