Skip to content

Instantly share code, notes, and snippets.

@eneajaho
Created February 3, 2022 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eneajaho/d27231d97981a01399bf3881943cd969 to your computer and use it in GitHub Desktop.
Save eneajaho/d27231d97981a01399bf3881943cd969 to your computer and use it in GitHub Desktop.
Click outside Angular directive
import { Directive, ElementRef, Output, EventEmitter, HostListener } from '@angular/core';
@Directive({ selector: '[clickOutside]' })
export class ClickOutsideDirective {
@Output() clickOutside = new EventEmitter<Event>();
constructor(private elementRef: ElementRef) {}
@HostListener('document:click', ['$event'])
public onClick(event: Event) {
const isClickedInside = this.elementRef.nativeElement.contains(event.target);
if (!isClickedInside) {
this.clickOutside.emit(event);
}
}
}
@eneajaho
Copy link
Author

eneajaho commented Feb 3, 2022

Usage:

  <button (click)="show = !show; $event.stopPropagation()">
    New movie
  </button>

  <div *ngIf="show" class="drop-down" (clickOutside)="show = false">
    <!-- Content here -->
  </div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment