Hide on click Outside of element angular 4

2020-03-25 16:35发布

问题:

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.