Created
February 3, 2022 20:03
-
-
Save eneajaho/d27231d97981a01399bf3881943cd969 to your computer and use it in GitHub Desktop.
Click outside Angular 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: '[clickOutside]' }) | |
export class ClickOutsideDirective { | |
@Output() clickOutside = new EventEmitter<Event>(); | |
constructor(private elementRef: ElementRef) {} | |
@HostListener('document:click', ['$event']) | |
public onClick(event: Event) { | |
const isClickedInside = this.elementRef.nativeElement.contains(event.target); | |
if (!isClickedInside) { | |
this.clickOutside.emit(event); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: