DebounceClick Directive

JS
S
JavaScript

Delay a button click. Replace (click) with (debounceClick)

1import { Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output } from '@angular/core';
2import { Subject } from 'rxjs';
3import { Subscription } from 'rxjs';
4import { debounceTime } from 'rxjs/operators';
5
6@Directive({
7  selector: '[debounceClick]',
8})
9export class DebounceClickDirective implements OnInit, OnDestroy {
10  @Input() debounceTime = 500;
11  @Output() debounceClick = new EventEmitter();
12  private clicks = new Subject();
13  private subscription: Subscription;
14
15  constructor() {}
16
17  ngOnInit() {
18    this.subscription = this.clicks.pipe(debounceTime(this.debounceTime)).subscribe((e) => this.debounceClick.emit(e));
19  }
20
21  ngOnDestroy() {
22    this.subscription.unsubscribe();
23  }
24
25  @HostListener('click', ['$event'])
26  clickEvent(event) {
27    event.preventDefault();
28    event.stopPropagation();
29    this.clicks.next(event);
30  }
31}
32

Created on 10/13/2020