我有一个指令,可以在点击时打开一个子菜单,但我想通过仅在单击目标元素时激活文档单击来改进它。所以问题是改进这个指令或如何动态添加主机监听器。
import { Directive, HostListener, Input, AfterContentInit, ElementRef, ViewContainerRef, ContentChild } from '@angular/core';
@Directive({
selector: '[appSubMenu]'
})
export class SubMenuDirective implements AfterContentInit {
private visible: boolean = false;
@ContentChild('subMenu') child: ElementRef;
constructor(private vcRef: ViewContainerRef) { }
ngAfterContentInit() {
this.child.nativeElement.style.display = 'none';
}
@HostListener('document:click', ['$event', '$event.target'])
show(event:MouseEvent, targetElem: HTMLElement): void {
if (this.vcRef.element.nativeElement === targetElem && !this.visible) {
this.child.nativeElement.style.display = 'block';
this.visible = true;
} else {
this.child.nativeElement.style.display = 'none';
this.visible = false;
}
}
}