I found this clickOut
directive:
https://github.com/chliebel/angular2-click-outside. I check it and it works well (i only copy clickOutside.directive.ts
to my project). U can use it in this way:
<div (clickOutside)="close($event)"></div>
Where close
is your function which will be call when user click outside div. It is very elegant way to handle problem described in question.
If you use above directive to close popUp window, remember first to add event.stopPropagation()
to button click event handler which open popUp.
Below i copy oryginal directive code from file clickOutside.directive.ts
(in case if link will stop working in future) - the author is Christian Liebel :
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';_x000D_
_x000D_
@Directive({_x000D_
selector: '[clickOutside]'_x000D_
})_x000D_
export class ClickOutsideDirective {_x000D_
constructor(private _elementRef: ElementRef) {_x000D_
}_x000D_
_x000D_
@Output()_x000D_
public clickOutside = new EventEmitter<MouseEvent>();_x000D_
_x000D_
@HostListener('document:click', ['$event', '$event.target'])_x000D_
public onClick(event: MouseEvent, targetElement: HTMLElement): void {_x000D_
if (!targetElement) {_x000D_
return;_x000D_
}_x000D_
_x000D_
const clickedInside = this._elementRef.nativeElement.contains(targetElement);_x000D_
if (!clickedInside) {_x000D_
this.clickOutside.emit(event);_x000D_
}_x000D_
}_x000D_
}
_x000D_