I have a demo here - https://stackblitz.com/edit/angular-lewrxv?file=app%2FClickElsewhereDirective.ts
I have a drop down menu that opens when the button is clicked.
Id like to close the menu when you click anywhere else.
I'm using a directive to emit an event when I click outside the menu.
The console log works before the event is emitted, but how can I use this to close the menu.
import { Directive, EventEmitter, ElementRef, HostListener, Output } from '@angular/core';
@Directive({ selector: '[clickElsewhere]' })
export class ClickElsewhereDirective {
@Output() clickElsewhere = new EventEmitter<MouseEvent>();
constructor(private elementRef: ElementRef) {}
@HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
const targetElement = event.target as HTMLElement;
// Check if the click was outside the element
if (targetElement && !this.elementRef.nativeElement.contains(targetElement)) {
console.log(event)
this.clickElsewhere.emit(event);
}
}
}