How can I close a dropdown on click outside? How can I close a dropdown on click outside? javascript javascript

How can I close a dropdown on click outside?


You can use (document:click) event:

@Component({  host: {    '(document:click)': 'onClick($event)',  },})class SomeComponent() {  constructor(private _eref: ElementRef) { }  onClick(event) {   if (!this._eref.nativeElement.contains(event.target)) // or some similar check     doSomething();  }}

Another approach is to create custom event as a directive. Check out these posts by Ben Nadel:


ELEGANT METHOD

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.

BONUS:

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 :