Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eneajaho/cf4709b6170d46110e89f83b1070d25e to your computer and use it in GitHub Desktop.
Save eneajaho/cf4709b6170d46110e89f83b1070d25e 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment