Created
November 7, 2016 21:33
-
-
Save 2J/c76660a788a5b0ce80e2c8234d1072c0 to your computer and use it in GitHub Desktop.
Angular 2 directive with event that fires when user clicks outside of element
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, HostListener, Output, OnInit, OnDestroy, ElementRef, EventEmitter } from '@angular/core'; | |
@Directive({ | |
selector: '[offClick]' | |
}) | |
export class OffClickDirective implements OnInit, OnDestroy { | |
@Output('offClick') public offClick: EventEmitter<null> = new EventEmitter<null>(); | |
constructor( | |
private elementRef: ElementRef | |
) { | |
this.documentClick = this.documentClick.bind(this); //bind scope to component | |
} | |
public documentClick($event: any): void { | |
if (!this.elementRef.nativeElement.contains($event.target)) { | |
this.offClick.emit(); | |
} | |
} | |
public ngOnInit(): void { | |
setTimeout(() => { document.addEventListener('click', this.documentClick); }, 0); | |
} | |
public ngOnDestroy(): void { | |
document.removeEventListener('click', this.documentClick); | |
} | |
} | |
/* | |
EXAMPLE: | |
<div (offClick)="someFunction()"></div> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment