Skip to content

Instantly share code, notes, and snippets.

@rob-balfre
Created April 19, 2017 21:45
Show Gist options
  • 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.

@HetRojivadiya
Copy link

In this Directive problem is when my drop down is closed and I click any when in my body this directive continuously emitting events. it cause performance issue. can we solved it?

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