If you want to implement a directive for debouncing events in Angular, you can create a custom directive like the one below. This example demonstrates how to debounce click events, but you can adapt it for any other type of event.
import { Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Directive({
selector: '[debounceClick]'
})
export class DebounceClickDirective implements OnInit, OnDestroy {
@Input()
public debounceClickTime = 500;
@Output()
public debounceClick = new EventEmitter();
private clicks = new Subject();
private subscription: Subscription;
constructor() { }
public ngOnInit() {
this.subscription = this.clicks.pipe(debounceTime(this.debounceClickTime)).subscribe((e: Event) =>
this.debounceClick.emit(e));
}
public ngOnDestroy() {
this.subscription.unsubscribe();
}
@HostListener('click', ['$event'])
public clickEvent(event: Event) {
event.preventDefault();
event.stopPropagation();
this.clicks.next(event);
}
}
To use this directive in your HTML template, follow the example below:
<input type="text" (debounceClick)="yourMethod()" debounceClickTime="1000" />
The debounceClickTime
attribute is optional. If not specified, the default debounce time is set to 500ms.