Created
August 13, 2018 15:31
-
-
Save seangwright/543ff55b5646664ffd179ad2a047d1af to your computer and use it in GitHub Desktop.
Vue-js style click event modifiers directive for Angular
This file contains 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, ElementRef, EventEmitter, OnInit, Output, Renderer2 } from '@angular/core'; | |
/** | |
* Sourced from https://netbasal.com/implementing-event-modifiers-in-angular-87e1a07969ce | |
*/ | |
@Directive({ | |
selector: | |
// tslint:disable-next-line:directive-selector | |
'[click.stop],[click.prevent],[click.stop.prevent],[click.prevent.stop]', | |
}) | |
export class ClickStopOrPreventDirective implements OnInit { | |
@Output('click.stop') | |
stopPropEvent = new EventEmitter(); | |
@Output('click.prevent') | |
preventDefaultEvent = new EventEmitter(); | |
@Output('click.stop.prevent') | |
stopAndPreventEvent = new EventEmitter(); | |
@Output('click.prevent.stop') | |
preventAndStopEvent = new EventEmitter(); | |
constructor(private renderer: Renderer2, private element: ElementRef) {} | |
ngOnInit() { | |
this.renderer.listen(this.element.nativeElement, 'click', event => | |
this.handleEvent(event), | |
); | |
} | |
private handleEvent(event: MouseEvent) { | |
if (this.stopPropEvent.observers.length > 0) { | |
event.stopPropagation(); | |
this.stopPropEvent.emit(event); | |
} else if (this.preventDefaultEvent.observers.length > 0) { | |
event.preventDefault(); | |
this.preventDefaultEvent.emit(event); | |
} else if (this.stopAndPreventEvent.observers.length > 0) { | |
event.stopPropagation(); | |
event.preventDefault(); | |
this.stopAndPreventEvent.emit(event); | |
} else if (this.preventAndStopEvent.observers.length > 0) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
this.preventAndStopEvent.emit(event); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment