How to detect click outside of an element in Angular?

前端 未结 7 771
死守一世寂寞
死守一世寂寞 2020-12-29 10:06

This div will be dynamically shown on the page as an east panel when the open panel button is clicked. The bool showEastPanel variable

7条回答
  •  旧巷少年郎
    2020-12-29 10:38

    I like the answer by Sujay. If you wish to create a directive instead (to be used in several components). This is how I would do it.

    import {
      Directive,
      EventEmitter,
      HostListener,
      Output,
      ElementRef,
    } from '@angular/core';
    
    @Directive({
      selector: '[outsideClick]',
    })
    export class OutsideClickDirective {
      @Output()
      outsideClick: EventEmitter = new EventEmitter();
    
      @HostListener('document:mousedown', ['$event'])
      onClick(event: MouseEvent): void {
        if (!this.elementRef.nativeElement.contains(event.target)) {
          this.outsideClick.emit(event);
        }
      }
    
      constructor(private elementRef: ElementRef) {}
    }
    

    You would then use the directive like so:

    
    

提交回复
热议问题