Skip to content

Instantly share code, notes, and snippets.

@chekit
Created July 10, 2018 14:48
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 chekit/0cfd0a09c927df3207dfbb517b711174 to your computer and use it in GitHub Desktop.
Save chekit/0cfd0a09c927df3207dfbb517b711174 to your computer and use it in GitHub Desktop.
Detect if the click was made outside host component
import { Component, ElementRef, HostListener } from '@angular/core';
/**
* If we need to detect where was click made outside the hosting component, we can use the construction below
* Source: https://stackoverflow.com/a/40107009
*/
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
@HostListener('document:click', ['$event']) onClickOutside({ target }) {
if (!this.elementRef.nativeElement.contains(target)) {
// do something if clicked outside hosting component
}
}
constructor(
private elementRef: ElementRef
) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment