How to detect click outside of an element in Angular?

前端 未结 7 786
死守一世寂寞
死守一世寂寞 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:53

    I have did the same in one of my requirement to show mega menu popup when user clicks on menu icon but want to close it whet user clicks outside it. Here i am trying to prevent click on icon as well. Please have a look.

    In HTML

     

    In TS

      @ViewChild('menuIcon', { read: ElementRef, static: false })  menuIcon: ElementRef;
      @ViewChild('menuPopup', { read: ElementRef, static: false })  menuPopup: ElementRef;
       showContainer = false;
    
          constructor(private renderer2: Renderer2) {
          this.renderer2.listen('window', 'click', (e: Event) => {
            if (
             (this.menuPopup && this.menuPopup.nativeElement.contains(e.target)) ||
              (this.menuIcon && this.menuIcon.nativeElement.contains(e.target))
             ) {
                  // Clicked inside plus preventing click on icon
                 this.showContainer = true;
               } else {
                 // Clicked outside
                 this.showContainer = false;
             }
          });
        }
    
         onMenuClick() {
            this.isShowMegaMenu = true;
          }
    

提交回复
热议问题