openaire-library/utils/click/click-outside-or-esc.direct...

34 lines
818 B
TypeScript
Raw Normal View History

import {Directive, ElementRef, EventEmitter, HostListener, Output} from '@angular/core';
export interface ClickEvent {
event: any,
clicked: boolean;
}
@Directive({
selector: '[click-outside-or-esc]'
})
export class ClickOutsideOrEsc {
@Output('clickOutside') clickOutside: EventEmitter<ClickEvent> = new EventEmitter<ClickEvent>();
constructor(private elementRef: ElementRef) {}
2022-04-17 14:30:21 +02:00
@HostListener('document:click', ['$event'])
click(event) {
if(event.isTrusted) {
this.clickOutside.emit({
event: event,
clicked: !(this.elementRef && this.elementRef.nativeElement.contains(event.target))
});
}
}
@HostListener('window:keydown.escape', ['$event'])
esc(event: KeyboardEvent) {
this.clickOutside.emit({
event: event,
clicked: true
});
}
}