单击隐藏在元素angular 4外部

问题描述:

我为垂直导航创建了一个侧边菜单,因此在单击时切换侧边菜单.我需要在该菜单外的任意位置单击以关闭该菜单.我尝试安装:

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

但是由于某种原因它不起作用,我运行npm install,添加

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

我没有使用该库,但是作为没有该库的解决方法,您可以在SideBar组件上附加click事件处理程序并切换sidebar的showFlag .并且在边栏中可以有* ngIf,其标志类型为

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