Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement