How to detect click outside of an element in Angular?

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

    i did other way unlike the previous answers.

    i put mouseleave, mouseenter event on dropdown menu

    
    
      constructor(private renderer: Renderer2) {
        /**
         * this.renderer instance would be shared with the other multiple same components
         * so you should have one more flag to divide the components
         * the only dropdown with mouseInFilter which is false should be close
         */
        this.renderer.listen('document', 'click', (e: Event) => {
          if (!this.mouseInFilter) {
            // this is the time to hide dropdownVisible
            this.dropdownVisible = false;
          }
        });
      }
    
      onMouseOutFilter(e) {
        this.mouseInFilter = false;
      }
    
      onMouseEnterFilter(e) {
        this.mouseInFilter = true;
      }
    

    and make sure the defaultValue of mouseInFilter is false;

      ngOnInit() {
        this.mouseInFilter = false;
        this.dropdownVisible = false;
      }
    

    and when dropdown should be visible mouseInFilter is going to be true

      toggleDropDownVisible() {
        if (!this.dropdownVisible) {
          this.mouseInFilter = true;
        }
        this.dropdownVisible = !this.dropdownVisible;
      }
    

提交回复
热议问题