Skip to content

Instantly share code, notes, and snippets.

@gildniy
Created December 12, 2017 02:57
Show Gist options
  • Save gildniy/ac64ea46d4c8f3a83b9554076ea130b0 to your computer and use it in GitHub Desktop.
Save gildniy/ac64ea46d4c8f3a83b9554076ea130b0 to your computer and use it in GitHub Desktop.
Angular 4 debounce click directive
import { Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import { debounceTime } from 'rxjs/operators';
@Directive({
selector: '[kiraDebounceClick]'
})
export class DebounceClickDirective implements OnInit, OnDestroy {
@Input() debounceTime = 500;
@Output() debounceClick = new EventEmitter();
private clicks = new Subject();
private subscription: Subscription;
constructor() {
}
ngOnInit() {
this.subscription = this.clicks.pipe(
debounceTime(this.debounceTime)
).subscribe(e => this.debounceClick.emit(e));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
@HostListener('click', ['$event'])
clickEvent(event) {
event.preventDefault();
event.stopPropagation();
this.clicks.next(event);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment