Skip to content

Instantly share code, notes, and snippets.

@rob-balfre
Created April 19, 2017 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rob-balfre/0c989ed6a4e131a09a684dabb649e0cd to your computer and use it in GitHub Desktop.
Save rob-balfre/0c989ed6a4e131a09a684dabb649e0cd to your computer and use it in GitHub Desktop.
Angular Click Outside Directive
import { Directive, ElementRef, Output, EventEmitter, HostListener } from '@angular/core';
@Directive({
selector: '[appClickOutside]'
})
export class ClickOutsideDirective {
@Output() appClickOutside: EventEmitter<any> = new EventEmitter();
constructor(private _elementRef: ElementRef) {
}
@HostListener('document:click', ['$event', '$event.target'])
public onClick($event, targetElement) {
const isClickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!isClickedInside) {
this.appClickOutside.emit($event);
}
}
}
<div class="menu" (click)="open()">
...
<div class="options" *ngIf="showList" (appClickOutside)="close($event)">
...
</div>
</div>
@alicelebidev
Copy link

Thanks for this! Found it pretty useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment