aboutsummaryrefslogtreecommitdiff
path: root/Timeline/ClientApp/src/app/debounce-click.directive.ts
blob: feb0404eb1a2630069d2dd88ade385b6fc9ac595 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { Directive, Output, Input, EventEmitter, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Directive({
  selector: '[appDebounceClick]'
})
export class DebounceClickDirective implements OnInit, OnDestroy {

  private subscription: Subscription;

  @Output('appDebounceClick') clickEvent = new EventEmitter<any>();

  // tslint:disable-next-line:no-input-rename
  @Input('appDebounceClickTime')
  set debounceTime(value: number) {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
    this.subscription = fromEvent(<HTMLElement>this.element.nativeElement, 'click').pipe(
      debounceTime(value)
    ).subscribe(o => this.clickEvent.emit(o));
  }

  constructor(private element: ElementRef) {
  }

  ngOnInit() {
    if (!this.subscription) {
      this.subscription = fromEvent(<HTMLElement>this.element.nativeElement, 'click').pipe(
        debounceTime(500)
      ).subscribe(o => this.clickEvent.emit(o));
    }
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}