-
-
Save eneajaho/cf4709b6170d46110e89f83b1070d25e to your computer and use it in GitHub Desktop.
Angular Click Outside Directive
This file contains hidden or 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, 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); | |
} | |
} | |
} |
This file contains hidden or 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
<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