feat: add focus by id
This commit is contained in:
28
src/directives/focus-next.directive.ts
Normal file
28
src/directives/focus-next.directive.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import {Directive, HostListener, Input} from '@angular/core';
|
||||
|
||||
@Directive({
|
||||
selector: '[focusNext]',
|
||||
standalone: true
|
||||
})
|
||||
export class FocusNextDirective {
|
||||
@Input('focusNext') nextElementSelector!: string;
|
||||
|
||||
@HostListener('keydown.enter', ['$event'])
|
||||
handleEnter(event: KeyboardEvent) {
|
||||
event.preventDefault();
|
||||
const nextElement = document.getElementById(this.nextElementSelector) as HTMLElement;
|
||||
if (nextElement) {
|
||||
nextElement.focus();
|
||||
|
||||
if (this.isClickable(nextElement)) {
|
||||
nextElement.click();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private isClickable(element: HTMLElement): boolean {
|
||||
const clickableTags = ['BUTTON', 'A', 'INPUT'];
|
||||
const hasTabIndex = element.hasAttribute('tabindex');
|
||||
return clickableTags.includes(element.tagName) || hasTabIndex;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user