Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {
- Directive,
- Input,
- Output,
- EventEmitter,
- ElementRef,
- OnDestroy
- } from '@angular/core';
- @Directive({
- selector: '[my-click-outside]'
- })
- export class ClickOutsideDirective implements OnDestroy {
- @Input()
- set 'my-click-outside'(shouldListen: boolean) {
- if (shouldListen) {
- document.addEventListener('click', this.onClick, { capture: true });
- } else {
- document.removeEventListener('click', this.onClick);
- }
- }
- @Output() clickOutside = new EventEmitter<void>();
- constructor(private elementRef: ElementRef) {}
- private onClick = (event: MouseEvent) => {
- const clickedInside = this.elementRef.nativeElement.contains(event.target);
- if (!clickedInside) {
- this.clickOutside.emit();
- }
- };
- ngOnDestroy() {
- document.removeEventListener('click', this.onClick);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement