I created a side menu for my vertical navigation, so I toggle the side-menu on click. I need to close that menu on click anywhere outside that menu. I tried installing :
https://github.com/chliebel/angular2-click-outside
But it doesn't work for some reason, I run npm install
, add the
(clickOutside)="close()"
to my component or side menu wrapper and nothing happens.
Any help please? The directive code:
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
constructor(private _elementRef: ElementRef) {
}
@Output()
public clickOutside = new EventEmitter<MouseEvent>();
@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {
if (!targetElement) {
return;
}
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.clickOutside.emit(event);
}
}
}