Angular 5 个自定义指令触发包裹到 *ngIf=false 中的元素

Angular 5 custom directive fires for element wrapped into *ngIf=false

我正在研究应该在点击外部后关闭下拉菜单的指令。具有指令的元素也具有 *ngIf 并且在单击时不在页面上,但指令仍在触发事件 - 因此下拉菜单永远不会打开,因为 showList 变为 false (click)="showList = true" 解雇后立即。我该如何避免这种情况?

stackblitz

import { Directive, HostListener, ElementRef, EventEmitter, Inject, PLATFORM_ID, Output, Input, OnInit, Renderer2, AfterContentInit } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Directive({
  selector: '[clickOutside]'
})
export class ClickOutsideDirective implements AfterContentInit {

  ngAfterContentInit(): void {
    this.contentInitialized = true;
  }
  @Input("clickOutside") config: any = {};
  @Output() clickOutside: EventEmitter<any> = new EventEmitter();
  private isBrowser: boolean = false;
  private isIE11: boolean = false;
  private contentInitialized: boolean = false;

  constructor(private renderer: Renderer2, private _el: ElementRef, @Inject(PLATFORM_ID) private platformId: any) {
    this.isBrowser = isPlatformBrowser(platformId);
    this.isIE11 = this.isBrowser && !!(window as any).MSInputMethodContext && !!(document as any).documentMode;
  }

  @HostListener('document:click', ['$event'])
  public onClick(event) {
    console.log("CLICKED");
    if (this.contentInitialized && !(this._el.nativeElement.contains(event.target) || (event.target == window.document.querySelector(this.config.excludeLocator)))) {
      this.clickOutside.emit(event);
    }
  }

  @HostListener('document:keyup', ['$event'])
  private onKeyup(event) {
    if (event.keyCode == 27) {
      this.clickOutside.emit(event);
    }
  }

}
<div class="menu-trigger" (click)="showList = true"></div>
<ul class="list" *ngIf="showList" (clickOutside)="showGiftList = false">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
</ul>

为了避免父事件 运行 你需要从子元素中停止它,你可以通过

$event.stopPropagation();

The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.

如果您想学习一些基础知识并进一步提高 HTML 活动,您可以查看 this