feat: add focus by id

This commit is contained in:
Polianin Nikita 2024-06-22 00:55:03 +03:00
parent 8d075f8982
commit e56644c538
2 changed files with 30 additions and 1 deletions

View File

@ -3,11 +3,12 @@ import {RouterOutlet} from '@angular/router';
import {FooterComponent} from "@component/common/footer/footer.component";
import localeRu from '@angular/common/locales/ru';
import { registerLocaleData } from '@angular/common';
import {FocusNextDirective} from "@/directives/focus-next.directive";
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, FooterComponent],
imports: [RouterOutlet, FooterComponent, FocusNextDirective],
template: `
<router-outlet/>
<app-footer/>`

View 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;
}
}