Click Debounce with Angular 2,4,6
Surprising that there is no directive present in angular for implementing debounce for search and clicks...
Some promising links:
Good directive:
https://coryrylan.com/blog/creating-a-custom-debounce-click-directive-in-angular
Only correction:
http://disq.us/p/1s8bi8c
So use throttleTime function instead of debounceTime:
https://reactive.how/throttletime
debounce time is better when doing search fields.
Final code for me looks like this.
-x-x-x-
Some promising links:
Good directive:
https://coryrylan.com/blog/creating-a-custom-debounce-click-directive-in-angular
Only correction:
http://disq.us/p/1s8bi8c
So use throttleTime function instead of debounceTime:
https://reactive.how/throttletime
debounce time is better when doing search fields.
Final code for me looks like this.
import { Directive, HostListener, OnInit, EventEmitter, Output, Input } from '@angular/core';
import { throttleTime } from 'rxjs/operators';
import { Subject, Subscription, Observable } from 'rxjs';
import { debounceTime } from 'rxjs/operator/debounceTime';
@Directive({
selector: '[clickDebounce]'
})
export class ClickDebounceDirective implements OnInit {
@Input() debounceTime = 500;
@Output() debounceClick = new EventEmitter();
private clicks: Subject<any> = new Subject();
private clickSub: Subscription;
constructor() { }
ngOnInit() {
this.clickSub = this.clicks.pipe(
throttleTime(this.debounceTime)
).subscribe(e => this.debounceClick.emit(e));
}
ngOnDestroy() {
this.clickSub.unsubscribe();
}
@HostListener('click', ['$event'])
clickEvent(event) {
event.preventDefault();
event.stopPropagation();
// console.log('Click from Host Element!');
this.clicks.next(event);
}
}
-x-x-x-

Comments
Post a Comment