Created
December 12, 2017 02:57
-
-
Save gildniy/ac64ea46d4c8f3a83b9554076ea130b0 to your computer and use it in GitHub Desktop.
Angular 4 debounce click 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 { 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