I have a directive that opens a sub menu on click, but I would like to improve it by only activate document click when the target element has been clicked on. So the question is to improve this directive or how to dynamically add host listener.
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;
}
}
}