Created
April 19, 2017 21:45
-
-
Save rob-balfre/0c989ed6a4e131a09a684dabb649e0cd 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
Thanks for this! Found it pretty useful.