From e56644c5382205ff73afd894b3bad14495aa5612 Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Sat, 22 Jun 2024 00:55:03 +0300 Subject: [PATCH] feat: add focus by id --- src/app/app.component.ts | 3 ++- src/directives/focus-next.directive.ts | 28 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 src/directives/focus-next.directive.ts diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 9a6cdf4..a35aebd 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -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: ` ` diff --git a/src/directives/focus-next.directive.ts b/src/directives/focus-next.directive.ts new file mode 100644 index 0000000..a01ee0c --- /dev/null +++ b/src/directives/focus-next.directive.ts @@ -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; + } +}