Hide on click Outside of element angular 4

空扰寡人 提交于 2019-12-01 08:17:25

问题


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

回答1:


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();
 }
}



回答2:


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.



来源:https://stackoverflow.com/questions/44043746/hide-on-click-outside-of-element-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!