Reputation: 1850
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);
}
}
}
Upvotes: 3
Views: 9832
Reputation: 390
That package doesn't support Angular 4. There is an updated package https://www.npmjs.com/package/ng-click-outside for Angular 4+.
I can confirm that package works in Angular 5.
Upvotes: 3
Reputation: 815
I have not used that library but as a workaround without the library what you can do is attach a click event handler on your SideBar component and toggle the showFlag of sidebar. And in the sidebar can have *ngIf with that flag type like
@Component({
host: {
'(document:click)': 'onClick($event)',
},
})
class SidebarComponent() {
constructor(private _el: ElementRef) { }
onClick(event) {
if (!this._el.nativeElement.contains(event.target)) // similar checks
resetShowFlagSidebar();
}
}
Upvotes: 11