Skip to content

Instantly share code, notes, and snippets.

@2J
Created November 7, 2016 21:33
Show Gist options
  • Save 2J/c76660a788a5b0ce80e2c8234d1072c0 to your computer and use it in GitHub Desktop.
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
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