簡體   English   中英

如何檢測Angular中元素外部的點擊?

[英]How to detect click outside of an element in Angular?

單擊open panel按鈕時,此div將作為東面板動態顯示在頁面上。 bool showEastPanel變量用於打開和關閉東面板。 我正在嘗試使用(clickoutside)關閉面板(將showEastPanel設置為 false),但是打開的面板首先在Angular掛鈎上運行,並且面板設置為 true 然后 false 並且面板不顯示。 是否有任何方法可以將clickoutside范圍clickoutside為不包含按鈕?

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

這是工作演示的鏈接: Stackblitz Demo

我會通過使用 Angular 推薦的方法來做到這一點,該方法也很容易在沒有 DOM 訪問的環境中開發應用程序,我的意思是Renderer 2類,它是 Angular 以服務形式提供的抽象,允許操作應用程序的元素而無需必須直接接觸 DOM。

在這種方法中,您需要將Renderer2注入到您的組件構造函數中, Renderer2可以讓我們優雅地listen觸發事件。 它只是將您要監聽的元素作為第一個參數,它可以是windowdocumentbody或任何其他元素引用。 對於第二個參數,它接受我們要監聽的事件,在這種情況下是click ,第三個參數實際上是我們通過箭頭函數執行的回調函數。

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

解決方案的其余部分很簡單,您只需要設置一個布爾標志來保持菜單(或面板)可見性的狀態,我們應該做的是在菜單外單擊時為該標志分配false

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

同樣,如果您想查看工作演示,請使用此鏈接: Stackblitz Demo

你可以做這樣的事情

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

並為面板使用 *ngIf=isOpen

我想添加幫助我獲得正確結果的解決方案。

當使用嵌入元素並且您想要檢測父級上的點擊時, event.target 提供對基本子級的引用。

HTML

<div #toggleButton (click)="toggleMenu()">
    <u>Toggle Menu</u>
    <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 的引用

對於這種情況,我使用了 M98 的解決方案,包括 Renderer2,但將條件更改為 Sujay 的回答中的條件。

ToggleButton.nativeElement.contains(e.target) 即使單擊事件的目標在 nativeElement 的子級中也返回true ,從而解決了問題。

組件.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;
    }
}

這是一個可重用的指令,它也涵蓋了元素在 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),它確保在使用指令的組件呈現后安排檢查。

有用的鏈接:

我喜歡 Sujay 的回答。 如果您希望創建一個指令(在多個組件中使用)。 這就是我要做的。

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) {}
}

然后你可以像這樣使用指令:

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

與以前的答案不同,我做了其他方式。

我把mouseleave , mouseenter事件放在下拉菜單上

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

我在我的一項要求中做了同樣的事情,當用戶點擊菜單圖標時顯示超級菜單彈出窗口,但想要關閉它,用戶點擊它之外。 在這里,我也試圖防止點擊圖標。 請看一看。

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

您可以使用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屬性),這非常重要,並且大多數提議的解決方案都沒有這樣做。 請參閱此處的源代碼。

感謝 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;
  }
}

帶有演示的更簡化代碼: StackBlitz

我做了一個通用功能來關閉外部點擊菜單,並防止在特定元素上觸發點擊時關閉。

HTML

<button (click)="toggleMenu(); preventCloseOnClick()">Toggle Menu</button>
<ul (click)="preventCloseOnClick()" *ngIf="menuOpen">
  <li>Menu 1</li>
  <li>Menu 2</li>
  <li>Menu 3</li>
  <li>Menu 4</li>
  <li>Menu 5</li>
</ul>

TS

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

export class AppComponent {
  menuOpen: boolean = false;
  menuBtnClick: boolean = false;

  constructor(private renderer: Renderer2) {
    this.renderer.listen('window', 'click', (e: Event) => {
      if (!this.menuBtnClick) {
        this.menuOpen = false;
      }
      this.menuBtnClick = false;
    });
  }
  toggleMenu() {
    this.menuOpen = !this.menuOpen;
  }
  preventCloseOnClick() {
    this.menuBtnClick = true;
  }
}

如果 click() 和 clickOutside() 同時被觸發,那么你必須參考

https://github.com/arkon/ng-click-outside/issues/31

它解決了我的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM