Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created September 5, 2019 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldpipowitch/b0e96d364636d0fa8946ccedd8954c33 to your computer and use it in GitHub Desktop.
Save donaldpipowitch/b0e96d364636d0fa8946ccedd8954c33 to your computer and use it in GitHub Desktop.
Angular directive to (conditionally) track clicks outside of an element
import {
Directive,
Input,
Output,
EventEmitter,
ElementRef,
OnDestroy
} from '@angular/core';
@Directive({
selector: '[my-click-outside]'
})
export class ClickOutsideDirective implements OnDestroy {
@Input()
set 'my-click-outside'(shouldListen: boolean) {
if (shouldListen) {
document.addEventListener('click', this.onClick, { capture: true });
} else {
document.removeEventListener('click', this.onClick);
}
}
@Output() clickOutside = new EventEmitter<void>();
constructor(private elementRef: ElementRef) {}
private onClick = (event: MouseEvent) => {
const clickedInside = this.elementRef.nativeElement.contains(event.target);
if (!clickedInside) {
this.clickOutside.emit();
}
};
ngOnDestroy() {
document.removeEventListener('click', this.onClick);
}
}
<div [my-click-outside]="shouldTrack" (clickOutside)="doSomething()">Hello</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment