click-outside.directive.ts (886B)
1 import { Directive, ElementRef, output, effect, inject } from '@angular/core'; 2 import { DOCUMENT } from '@angular/common'; 3 4 @Directive({ 5 selector: '[clickOutside]', 6 standalone: true, 7 }) 8 export class ClickOutsideDirective { 9 private el = inject(ElementRef); 10 private document = inject(DOCUMENT); 11 clickOutside = output<boolean>(); 12 13 constructor() { 14 effect(() => { 15 const clickHandler = (event: MouseEvent) => { 16 if (!this.el.nativeElement.contains(event.target as Node)) { 17 this.clickOutside.emit(true); 18 } 19 }; 20 this.document.addEventListener('click', clickHandler); 21 22 // The function returned from effect is its cleanup function, 23 // which automatically removes the listener when the component is destroyed. 24 return () => { 25 this.document.removeEventListener('click', clickHandler); 26 }; 27 }); 28 } 29 }