Blog>
Snippets

Building an Angular Directive for ClickOutside

Showcase the creation of a custom directive as a standalone component to handle click outside events for dropdowns and modals.
import { Directive, ElementRef, Output, EventEmitter, HostListener } from '@angular/core';

@Directive({
  selector: '[clickOutside]'
})
export class ClickOutsideDirective {

  @Output() public clickOutside = new EventEmitter<MouseEvent>();

  constructor(private _elementRef: ElementRef) { }

  @HostListener('document:click', ['$event', '$event.target'])
  public onClick(event: MouseEvent, targetElement: HTMLElement): void {
    if (!targetElement) {
      return;
    }

    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this.clickOutside.emit(event);
    }
  }

}
This Angular directive named 'ClickOutsideDirective' is designed to detect clicks outside of the component it's applied to. The @Directive decorator defines the selector 'clickOutside' which can be used to attach this directive to an element. An event emitter 'clickOutside' is defined which emits an event when a click is detected outside the component. The constructor initializes with an ElementRef to access the element this directive is attached to. A HostListener is set up for clicks on the document, which triggers the 'onClick' method to determine if the click occurred outside and emits the clickOutside event if so.