This div will be dynamically shown on the page as an east panel when the open panel button is clicked. The bool showEastPanel variable
I like the answer by Sujay. If you wish to create a directive instead (to be used in several components). This is how I would do it.
import {
Directive,
EventEmitter,
HostListener,
Output,
ElementRef,
} from '@angular/core';
@Directive({
selector: '[outsideClick]',
})
export class OutsideClickDirective {
@Output()
outsideClick: EventEmitter = new EventEmitter();
@HostListener('document:mousedown', ['$event'])
onClick(event: MouseEvent): void {
if (!this.elementRef.nativeElement.contains(event.target)) {
this.outsideClick.emit(event);
}
}
constructor(private elementRef: ElementRef) {}
}
You would then use the directive like so: