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

36 lines
864 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) {}
@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', ['$event'])
keyEvent(event: KeyboardEvent) {
if(event.code === 'Escape') {
this.clickOutside.emit({
event: event,
clicked: true
});
}
}
}