Mark Letters
Mark Letters

Reputation: 333

dispatchEvent not working with KeyboardEvents (Angular 4)

I am trying to listen for the down arrow key and fire a tab event in its place.

My template contains this

<li #elRef 
    *ngFor="let handler of clickHandlers"
    (click)="doClickHandlerAction(handler)"
    (keydown)="checkArrowKey($event, elRef)">

And my component contains the following

checkArrowKey(event: KeyboardEvent, el) {
    if (event.keyCode === 40) {
      event.preventDefault();

      let keyboardEvent = new KeyboardEvent('keydown', {
        "code": "9",
      });

      el.dispatchEvent(keyboardEvent);
    }
    if (event.keyCode === 9) {
      console.log("tab key pressed");
    }
  }

When the down arrow key is pressed it dispatches the event but the element does not seem to receive the event. The if statement at the bottom checks if the tab key was pressed but this does not get called after the event was dispatched.

Interestingly, if I replace the keyboardEvent with a MouseEvent such as the following

let clickEvent = new MouseEvent('click', {bubbles: true});

My doClickHandlerAction() function will get called, indicating that the problem is with the KeyboardEvent.

Upvotes: 4

Views: 9516

Answers (1)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37413

it seems that (keydown) event work on focusable elements only such as input and textarea so add tabindex="0" attribute on li to add the focus behavior:

<li #elRef 
    *ngFor="let handler of [1,2,3]" 
    (keydown)="checkArrowKey($event, elRef)" tabindex="0"> hh </li>

also when you dispatch an event the keyCode value become 0, so use event.code to read the key code :

checkArrowKey(event: KeyboardEvent, el) {

    if (event.keyCode === 40) {
      event.preventDefault();

      let keyboardEvent = new KeyboardEvent('keydown', {
        "code": "9",
      });

      el.dispatchEvent(keyboardEvent);
    }
    if (event.keyCode === 9 || event.code === '9') {
      console.log("tab key pressed");
    }
  }

Demo

Upvotes: 1

Related Questions