import { EventManager } from '@angular/platform-browser'; import { Directive, ElementRef, Injector, OnInit, AfterViewInit } from '@angular/core'; @Directive({ selector: 'shortcut-tab', }) export class ShortCutTabKeyDirective implements OnInit, AfterViewInit { constructor(public el: ElementRef, public injector: Injector, private eventManager: EventManager) {} ngOnInit() { } ngAfterViewInit() { this.eventManager.addEventListener(this.el.nativeElement, 'keydown', (e: KeyboardEvent) => { e.stopPropagation(); if (e.key === 'Tab') { this.onTabKeydownHandler(e.target); } }); } private onTabKeydownHandler(currentTarget) { let allInputs = this.el.nativeElement.querySelectorAll('input,textarea'); allInputs = Array.from(allInputs); const currentInputIndex = allInputs.findIndex(n => n === currentTarget); let nextInputIndex = currentInputIndex + 1; if (nextInputIndex >= allInputs.length) { nextInputIndex = 0; } const nextInputTarget = allInputs[nextInputIndex]; if (nextInputTarget) { setTimeout(() => { nextInputTarget.focus(); }); } } }