Skip to content

Instantly share code, notes, and snippets.

@CobyBoy
Forked from Rwin90/click-outside.directive.ts
Created February 12, 2024 17:13
Show Gist options
  • Save CobyBoy/d3b530ccd9abc7580befbfce98f477ce to your computer and use it in GitHub Desktop.
Save CobyBoy/d3b530ccd9abc7580befbfce98f477ce to your computer and use it in GitHub Desktop.
angular 4 directive that emit an event when click event happen outside of target
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';
@Directive({
selector: '[appClickOutside]'
})
export class ClickOutsideDirective {
constructor(private _elementRef: ElementRef) {
}
@Output()
public clickOutside = new EventEmitter();
@HostListener('document:click' , ['$event.target']) onClick( target) {
const clickedInside = this._elementRef.nativeElement.contains(target);
if (!clickedInside) {
this.clickOutside.emit(null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment