Created
June 3, 2019 22:01
-
-
Save avoliva/b7c80d77e93717653164f73c36da6d2f to your computer and use it in GitHub Desktop.
Angular debounce directive
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
import { EventEmitter, ElementRef, OnInit, Directive, Input, Output } from '@angular/core'; | |
import { fromEvent } from 'rxjs'; | |
import { map, debounceTime } from 'rxjs/operators'; | |
import { NgModel } from '@angular/forms'; | |
@Directive({ selector: '[debounce]' }) | |
export class Debounce implements OnInit { | |
@Input() delay: number = 700; | |
@Input() eventName: string = 'keyup'; | |
@Output() func: EventEmitter<any> = new EventEmitter(); | |
constructor(private elementRef: ElementRef, private model: NgModel) { | |
} | |
ngOnInit(): void { | |
const eventStream = fromEvent(this.elementRef.nativeElement, this.eventName).pipe( | |
map(() => this.model.value), | |
debounceTime(this.delay) | |
) | |
eventStream.subscribe(input => this.func.emit(input)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: