chekit
7/10/2018 - 2:48 PM

Detect if the click was made outside host component

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
	) { }

}