-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclick-outside.directive.ts
More file actions
30 lines (25 loc) · 1003 Bytes
/
click-outside.directive.ts
File metadata and controls
30 lines (25 loc) · 1003 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { Directive, effect, ElementRef, inject, input, output } from '@angular/core'
import { UIEventService } from '@shiftcode/ngx-core'
/**
* Standalone Directive to listen for 'outside' element clicks
*/
@Directive({ selector: '[scClickOutside]', standalone: true })
export class ClickOutsideDirective {
readonly disabled = input(false, { alias: 'scClickOutsideDisabled' })
readonly scClickOutside = output<Event>()
private readonly element: HTMLElement = inject(ElementRef).nativeElement
private readonly uiEventService = inject(UIEventService)
constructor() {
effect((onCleanup) => {
if (!this.disabled()) {
const sub = this.uiEventService.forEvent(['click', 'touchstart']).subscribe(this.handleDocumentClick)
onCleanup(() => sub.unsubscribe())
}
})
}
private handleDocumentClick = (event: Event) => {
if (!(this.element === event.target || this.element.contains(<Node>event.target))) {
this.scClickOutside.emit(event)
}
}
}