2019-10-10 14:13:01 +02:00
|
|
|
import {Directive, OnInit, OnDestroy, Output, EventEmitter, ElementRef, Input} from '@angular/core';
|
2019-10-04 10:45:51 +02:00
|
|
|
import {Observable} from 'rxjs/Observable';
|
|
|
|
import 'rxjs/add/observable/fromEvent';
|
|
|
|
import 'rxjs/add/operator/delay';
|
|
|
|
import 'rxjs/add/operator/do';
|
2019-10-09 11:53:59 +02:00
|
|
|
import {Subscriber} from "rxjs";
|
2019-10-04 10:45:51 +02:00
|
|
|
|
|
|
|
@Directive({
|
|
|
|
selector: '[click-outside-or-esc]'
|
|
|
|
})
|
|
|
|
|
|
|
|
export class ClickOutsideOrEsc implements OnInit, OnDestroy {
|
|
|
|
private listening: boolean;
|
2019-10-09 11:53:59 +02:00
|
|
|
private subscriptions: any[] = [];
|
2019-10-10 14:13:01 +02:00
|
|
|
@Input()
|
|
|
|
public targetId = null;
|
2019-11-22 09:51:17 +01:00
|
|
|
@Input()
|
|
|
|
public escClose = true;
|
2019-10-04 10:45:51 +02:00
|
|
|
|
|
|
|
@Output('clickOutside') clickOutside: EventEmitter<Object>;
|
|
|
|
|
|
|
|
constructor(private _elRef: ElementRef) {
|
|
|
|
this.listening = false;
|
|
|
|
this.clickOutside = new EventEmitter();
|
|
|
|
}
|
|
|
|
|
|
|
|
ngOnInit() {
|
2019-10-09 11:53:59 +02:00
|
|
|
if(typeof document !== 'undefined') {
|
|
|
|
this.subscriptions.push(Observable
|
|
|
|
.fromEvent(document, 'click')
|
|
|
|
.delay(1)
|
|
|
|
.do(() => {
|
|
|
|
this.listening = true;
|
|
|
|
}).subscribe((event: MouseEvent) => {
|
|
|
|
this.onGlobalClick(event);
|
|
|
|
}));
|
|
|
|
this.subscriptions.push(Observable
|
|
|
|
.fromEvent(document, 'keydown')
|
|
|
|
.delay(1)
|
|
|
|
.do(() => {
|
|
|
|
this.listening = true;
|
|
|
|
}).subscribe((event: KeyboardEvent) => {
|
2019-11-22 09:51:17 +01:00
|
|
|
if (event.keyCode === 27 && this.escClose) {
|
2019-10-09 11:53:59 +02:00
|
|
|
this.clickOutside.emit({
|
|
|
|
target: (event.target || null),
|
|
|
|
value: true
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
}
|
2019-10-04 10:45:51 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
ngOnDestroy() {
|
2019-10-09 11:53:59 +02:00
|
|
|
if (this.subscriptions) {
|
|
|
|
this.subscriptions.forEach((subscription: Subscriber<any>) => {
|
|
|
|
subscription.unsubscribe();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
this.subscriptions = [];
|
2019-10-04 10:45:51 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
onGlobalClick(event: MouseEvent) {
|
|
|
|
if (event instanceof MouseEvent && this.listening === true) {
|
2019-10-10 18:38:20 +02:00
|
|
|
if (event.target['id'] != this.targetId) {
|
2019-10-04 10:45:51 +02:00
|
|
|
this.clickOutside.emit({
|
|
|
|
target: (event.target || null),
|
|
|
|
value: false
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
this.clickOutside.emit({
|
|
|
|
target: (event.target || null),
|
|
|
|
value: true
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|