Created
July 10, 2018 14:48
-
-
Save chekit/0cfd0a09c927df3207dfbb517b711174 to your computer and use it in GitHub Desktop.
Detect if the click was made outside host component
This file contains 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 { 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