SHARE
TWEET

Untitled

a guest Sep 16th, 2019 75 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {
  2.   Directive,
  3.   Input,
  4.   Output,
  5.   EventEmitter,
  6.   ElementRef,
  7.   OnDestroy
  8. } from '@angular/core';
  9.  
  10. @Directive({
  11.   selector: '[my-click-outside]'
  12. })
  13. export class ClickOutsideDirective implements OnDestroy {
  14.   @Input()
  15.   set 'my-click-outside'(shouldListen: boolean) {
  16.     if (shouldListen) {
  17.       document.addEventListener('click', this.onClick, { capture: true });
  18.     } else {
  19.       document.removeEventListener('click', this.onClick);
  20.     }
  21.   }
  22.  
  23.   @Output() clickOutside = new EventEmitter<void>();
  24.  
  25.   constructor(private elementRef: ElementRef) {}
  26.  
  27.   private onClick = (event: MouseEvent) => {
  28.     const clickedInside = this.elementRef.nativeElement.contains(event.target);
  29.     if (!clickedInside) {
  30.       this.clickOutside.emit();
  31.     }
  32.   };
  33.  
  34.   ngOnDestroy() {
  35.     document.removeEventListener('click', this.onClick);
  36.   }
  37. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top