Created
November 16, 2021 07:49
-
-
Save nivrith/154a5929826da1bff98ce0e594b9b922 to your computer and use it in GitHub Desktop.
Bind Single and Double Click events in Angular without clashing or bubbling issues
This file contains hidden or 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, Subscription } from 'rxjs'; | |
import { debounceTime } from 'rxjs/operators'; | |
@Directive({ | |
selector: '[click.single],[click.double]', | |
}) | |
export class ClickDoubleDirective implements OnInit, OnDestroy { | |
@Input() debounceTime = 300; | |
@Output('click.double') doubleClick = new EventEmitter(); | |
@Output('click.single') singleClick = new EventEmitter(); | |
private clicksSubject = new Subject<MouseEvent>(); | |
private subscription: Subscription; | |
constructor() {} | |
ngOnInit() { | |
this.subscription = this.clicksSubject.pipe(debounceTime(this.debounceTime)).subscribe(event => { | |
if (event.type === 'click') { | |
this.singleClick.emit(event); | |
} else { | |
this.doubleClick.emit(event); | |
} | |
}); | |
} | |
ngOnDestroy() { | |
this.subscription.unsubscribe(); | |
} | |
@HostListener('click', ['$event']) | |
clickEvent(event: MouseEvent) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
this.clicksSubject.next(event); | |
} | |
@HostListener('dblclick', ['$event']) | |
doubleClickEvent(event: MouseEvent) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
this.clicksSubject.next(event); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment