Angular 5自定义指令针对包裹在* ngIf = false中的元素触发

时间:2018-08-21 10:51:58

标签: angular angular5 angular2-directives angular-directive

我正在研究在外部单击后应关闭下拉菜单的指令。具有指令的元素也具有*ngIf,并且在单击时不显示在页面上,但是指令仍在触发事件-因此,当showList变为{{1}时,下拉菜单永远不会打开},false被解雇之后。如何避免这种情况?

stackblitz

(click)="showList = true"
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);
    }
  }

}

1 个答案:

答案 0 :(得分:1)

要避免运行父级事件,您需要从子元素中停止该事件,您可以通过

$event.stopPropagation();
  

event.stopPropagation()方法停止将事件冒泡到   父元素,防止任何父事件处理程序被   被执行。

如果您想学习一些基础知识并进一步学习 HTML事件,可以签出this