Skip to content

Instantly share code, notes, and snippets.

@avoliva
Created June 3, 2019 22:01
Show Gist options
  • Save avoliva/b7c80d77e93717653164f73c36da6d2f to your computer and use it in GitHub Desktop.
Save avoliva/b7c80d77e93717653164f73c36da6d2f to your computer and use it in GitHub Desktop.
Angular debounce directive
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));
}
}
@avoliva
Copy link
Author

avoliva commented Jun 3, 2019

Example:

<input debounce [delay]="300" type="text" name="term"  #term (func)="doThing(term.value)" [(ngModel)]="searchTerm" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment