如何在Angular 7中检测元素外部的单击?

时间:2018-07-03 08:55:21

标签: html angular

单击div按钮时,此open panel将在页面上动态显示为东面板。布尔showEastPanel变量是用于打开和关闭东部面板的变量。我正在尝试使用(clickoutside)关闭面板(将showEastPanel设置为false),但是打开的面板首先在Angular钩上运行,并且面板设置为true,然后设置为false,并且面板不显示。有什么办法使“ clickoutside”范围不包括按钮?

<div [ngClass]="{'d-none': !showEastPanel, 'east-panel-container': showEastPanel}" (clickOutside)="ClosePanel()">
<div id="east-panel">
  <ng-template #eastPanel></ng-template>
</div>

<button (click)="ShowPanel()">Open Panel</button>

9 个答案:

答案 0 :(得分:7)

我将使用Angular推荐的方法来做到这一点,该方法在没有DOM访问的环境中也很容易开发应用程序,我的意思是Renderer 2类是Angular提供的一种抽象形式,其服务形式允许无需直接触摸DOM即可操作应用程序的元素。

在这种方法中,您需要将Renderer2注入到组件构造函数中,Renderer2使我们能够listen优雅地触发事件。它只是将要监听的元素作为第一个参数,可以是windowdocumentbody或任何其他元素引用。对于第二个参数,我们需要监听事件,在本例中为click,而第三个参数实际上是我们使用箭头函数执行的回调函数。

this.renderer.listen('window', 'click',(e:Event)=>{ // your code here})

该解决方案的其余部分很容易,您只需要设置一个布尔标志即可保持菜单(或面板)可见性的状态,我们应该做的就是在该标志分配false时在菜单之外单击。

这是Stackblitz Demo

的链接

HTML

<button #toggleButton (click)="toggleMenu()"> Toggle Menu</button>

<div class="menu" *ngIf="isMenuOpen" #menu>
I'm the menu. Click outside to close me
</div>

app.component.ts

export class AppComponent {
  /**
   * This is the toogle button elemenbt, look at HTML and see its defination
   */
  @ViewChild('toggleButton') toggleButton: ElementRef;
  @ViewChild('menu') menu: ElementRef;

  constructor(private renderer: Renderer2) {
    /**
     * This events get called by all clicks on the page
     */
    this.renderer.listen('window', 'click',(e:Event)=>{
         /**
          * Only run when toggleButton is not clicked
          * If we don't check this, all clicks (even on the toggle button) gets into this
          * section which in the result we might never see the menu open!
          * And the menu itself is checked here, and it's where we check just outside of
          * the menu and button the condition abbove must close the menu
          */
        if(e.target !== this.toggleButton.nativeElement && e.target!==this.menu.nativeElement){
            this.isMenuOpen=false;
        }
    });
  }

  isMenuOpen = false;

  toggleMenu() {
    this.isMenuOpen = !this.isMenuOpen;
  }
}

答案 1 :(得分:1)

您可以做这样的事情

  @HostListener('document:mousedown', ['$event'])
  onGlobalClick(event): void {
     if (!this.elementRef.nativeElement.contains(event.target)) {
        // clicked outside => close dropdown list
     this.isOpen = false;
     }
  }

并在面板上使用* ngIf = isOpen

答案 2 :(得分:1)

我想添加有助于我获得适当结果的解决方案。

在使用嵌入式元素时,如果要检测对父元素的单击,event.target会引用基本子元素。

HTML

<div #toggleButton (click)="toggleMenu()">
    <b>Toggle Menu</b>
    <span class="some-icon"></span>
</div>

<div #menu class="menu" *ngIf="isMenuOpen">
    <h1>I'm the menu.</h1>
    <div>
        I have some complex content containing multiple children.
        <i>Click outside to close me</i>
    </div>
</div>

我点击“切换菜单” 文本,event.target返回对'u'元素的引用,而不是 #toggleButton div。< / p>

在这种情况下,我使用了包括Renderer2在内的M98解决方案,但将条件从Sujay的回答改为了。

即使单击事件的目标位于nativeElement的子级中,

ToggleButton.nativeElement.contains(e.target)也返回 true

component.ts

export class AppComponent {
/**
 * This is the toogle button element, look at HTML and see its definition
 */
    @ViewChild('toggleButton') toggleButton: ElementRef;
    @ViewChild('menu') menu: ElementRef;
    isMenuOpen = false;

    constructor(private renderer: Renderer2) {
    /**
     * This events get called by all clicks on the page
     */
        this.renderer.listen('window', 'click',(e:Event)=>{
            /**
             * Only run when toggleButton is not clicked
             * If we don't check this, all clicks (even on the toggle button) gets into this
             * section which in the result we might never see the menu open!
             * And the menu itself is checked here, and it's where we check just outside of
             * the menu and button the condition abbove must close the menu
             */
            if(!this.toggleButton.nativeElement.contains(e.target) && !this.menu.nativeElement.contains(e.target)) {
                this.isMenuOpen=false;
            }
        });
    }

    toggleMenu() {
        this.isMenuOpen = !this.isMenuOpen;
    }
}

答案 3 :(得分:0)

这是一个可重用的指令,它还涵盖了元素是否位于ngIf内部的情况:

import { Directive, ElementRef, Optional, Inject, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
import { DOCUMENT } from '@angular/common';
import { filter } from 'rxjs/operators';

@Directive({
  selector: '[outsideClick]',
})
export class OutsideClickDirective implements OnInit, OnDestroy {
  @Output('outsideClick') outsideClick = new EventEmitter<MouseEvent>();

  private subscription: Subscription;

  constructor(private element: ElementRef, @Optional() @Inject(DOCUMENT) private document: any) {}

  ngOnInit() {
    setTimeout(() => {
      this.subscription = fromEvent<MouseEvent>(this.document, 'click')
        .pipe(
          filter(event => {
            const clickTarget = event.target as HTMLElement;
            return !this.isOrContainsClickTarget(this.element.nativeElement, clickTarget);
          }),
        )
        .subscribe(event => this.outsideClick.emit());
    }, 0);
  }

  private isOrContainsClickTarget(element: HTMLElement, clickTarget: HTMLElement) {
    return element == clickTarget || element.contains(clickTarget);
  }

  ngOnDestroy() {
    if (this.subscription) this.subscription.unsubscribe();
  }
}

贷记https://github.com/ngez/platform,我从中得到了大部分的逻辑。

我所缺少的是setTimeout(...,0),它确保在呈现使用指令的组件之后安排检查。

有用的链接:

答案 4 :(得分:0)

我有一项要求,当用户单击菜单图标时要显示大型菜单弹出窗口,但要在用户单击菜单外部按钮时将其关闭,则必须执行相同的操作。 在这里,我也试图防止单击图标。请看看。

在HTML中

 <div #menuIcon (click)="onMenuClick()">
  <a><i class="fa fa-reorder"></i></a>
 </div>
<div #menuPopup  *ngIf="showContainer">
   <!-- Something in the popup like menu -->
</div>

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

答案 5 :(得分:0)

我做其他方式与以前的答案不同。

我在下拉菜单上放置了mouseleavemouseenter事件

<div
    class="dropdown-filter"
    (mouseleave)="onMouseOutFilter($event)"
    (mouseenter)="onMouseEnterFilter($event)"
  >
    <ng-container *ngIf="dropdownVisible">
      <input
        type="text"
        placeholder="search.."
        class="form-control"
        [(ngModel)]="keyword"
        id="myInput"
        (keyup)="onKeyUp($event)"
      />
    </ng-container>
    <ul
      class="dropdown-content"
      *ngIf="dropdownVisible"
    >
      <ng-container *ngFor="let item of filteredItems; let i = index">
        <li
          (click)="onClickItem($event, item)"
          [ngStyle]="listWidth && {width: listWidth + 'px'}"
        >
          <span>{{ item.label }}</span>
        </li>
      </ng-container>
    </ul>
  </div>
  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;
  }

并确保mouseInFilter的defaultValue为false;

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

以及何时应该显示下拉菜单时mouseInFilter将为真

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

答案 6 :(得分:0)

我喜欢Sujay的回答。如果您想创建一个指令(将在多个组件中使用)。这就是我要做的。

a
b
a
b

然后您将使用如下指令:

import {
  Directive,
  EventEmitter,
  HostListener,
  Output,
  ElementRef,
} from '@angular/core';

@Directive({
  selector: '[outsideClick]',
})
export class OutsideClickDirective {
  @Output()
  outsideClick: EventEmitter<MouseEvent> = 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) {}
}

答案 7 :(得分:0)

您可以使用 https://github.com/arkon/ng-click-outside,它非常易于使用,具有许多有用的功能:

@Component({
  selector: 'app',
  template: `
    <div (clickOutside)="onClickedOutside($event)">Click outside this</div>
  `
})
export class AppComponent {
  onClickedOutside(e: Event) {
    console.log('Clicked outside:', e);
  }
}

关于性能,当指令未激活时,lib 使用 ngOnDestroy 删除侦听器(使用 clickOutsideEnabled 属性),这非常重要并且大多数建议的解决方案不要那样做。请参阅源代码 here

答案 8 :(得分:0)

感谢 Emerica ng-click-outside 工作完美,这就是我需要的,我正在测试我的模态,但是当我点击它时,第一次点击按钮,它检测到外部点击,然后没有工作在模态上,但我只从文档中添加了 delayClickOutsideInit="true" 并且效果很好,这是最终结果:

<button
  (click)="imageModal()"
>
<button/>

<div
  *ngIf="isMenuOpen"
>
  <div
    (clickOutside)="onClickedOutside($event)"
    delayClickOutsideInit="true"
  >
   Modal content
  </div>
</div>

这是我的组件

import {
  Component,
} from '@angular/core';

@Component({
  selector: 'app-modal-header',
  templateUrl: './modal-header.component.html',
  styleUrls: ['./modal-header.component.css'],
})
export class ModalHeaderComponent implements OnInit {
  public isMenuOpen = false;

  constructor() {}

  imageModal() {
    this.isMenuOpen = !this.isMenuOpen;
  }
  closeModal() {
//you can do an only close function click
    this.isMenuOpen = false;
  }
  onClickedOutside(e: Event) {
    this.isMenuOpen = false;
  }
}