On keydown trigger next tab index (focus next element)

10,897

so, for the reference, there is obviously a distinction between Element and HTMLElement, the later is extended one.

Angular2 has a ElementRef you usually use when referencing an HTML element...

so to get a HTMLElement from event.nextSibling you do

let next = new ElementRef(event.nextSibling);

and the using

next.nativeElement.focus();

don't forget to include ElementRef in your imports

import { Component, ElementRef } from '@angular/core';
Share:
10,897
DS_web_developer
Author by

DS_web_developer

Updated on June 04, 2022

Comments

  • DS_web_developer
    DS_web_developer almost 2 years

    I am having a bootstrap's dropdown menu (I implemented only styles without Javascript)... hence I need to port to angular2 some js functionality.

    One is keyboard accessibility.

    So far I have:

    <div (keydown)="onMenuKeydown($event)" ....>
        <ul class="dropdown-menu">
            <li><a href="#"...>option 1</a></li>
            <li><a href="#"...>option 2</a></li>
            <li><a href="#"...>option 3</a></li>
        </ul>
    </div>
    

    In my controller I have this:

    onMenuKeydown(event: KeyboardEvent){
        if(event.keyCode === 40){
            /*event.srcElement.nextSibling.*/
            event.preventDefault();
        }
    }
    

    What I would like is that on arrow down it simulates or triggers the TAB key (so it should focus next element) and on arrow key up to simulate the SHIFT-TAB key (previous tabindex)

    I have the event.srcElement and have nextSiblingproperty but it doesn't have the method focus... so cannot do event.srcElement.nextSibling.focus();.

    What would be the best solution here?

  • TheDoozyLulu
    TheDoozyLulu over 4 years
    Could you please explain this @DS_web_developer , as I am also facing the same issue. I tried using tabindex but it fails to work in IE. It works only when tabindex=1, but only one time. Then the focus will get disappear once the list is over.