22

I have table and I'd like to add a function that will be triggered by the down arrow and cause the next row to become selected. So I'd like a down arrow, anywhere, to trigger a function in the component. I'm not concerned with the selection I know how to do that in a function, that was just my particular use case. I was just wondering how I can run a function when the user uses down arrow anywhere on the component or page?

I see how to do it on an input but can I bind it to a page or component so that a key down near the table will trigger an event?

Zachscs
  • 3,353
  • 7
  • 27
  • 52
  • 1
    See https://stackoverflow.com/a/37363257/4941860 . Use keydown instead of keypress. And remove `document:` to restrict it to the current component or element. Also see https://alligator.io/angular/binding-keyup-keydown-events/ – matmo Jan 19 '18 at 01:18

3 Answers3

29

You will get the keyup event from the HostListener decorator. For every keyup event there is a keycode associate with the event. You can use that keycode to distinguish between the down arrow key press among all the key events for other keys.

export class AppComponent {
  @HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    if(event.keyCode == KEY_CODE.DOWN_ARROW){
      // Your row selection code
      console.log(event);
    }
  }
}

export enum KEY_CODE {
    UP_ARROW = 38,
    DOWN_ARROW = 40,
    RIGHT_ARROW = 39,
    LEFT_ARROW = 37
}

Use the above code in the component where you are displaying the table. I used AppComponent just to demonstrate

Ashraful Islam
  • 1,228
  • 10
  • 13
13

event.keyCode has been deprecated

You can use event.key instead

    @HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    if(event.key == 'ArrowDown'){
      // Your row selection code
      console.log(event.key);
    }
  }
matel
  • 425
  • 5
  • 12
0
        var key = e.keyCode;
        if(key === 8){ /* If backspace is pressed*/
          if(this.value.length === 3 || this.value.length === 6){
            /*if next char to be removed is /' remove last two characters from input value*/
            this.value = this.value.substr(0, this.value.length-1);
          }
          /*remove last character*/
          this.value = this.value.substr(0, this.value.length);
        }
        /*if key pressed is not number or input got date*/
        else if( !((key > 47 && key < 58) || (key > 95 && key < 106)) 
              || this.value.length === 10){
          e.preventDefault(); //no nothing
        }
      });

      function autoSlash(veiwvalue){
        if(veiwvalue.length === 2 || veiwvalue.length === 5){
          veiwvalue += '/';
        }
        ngModelController.$setViewValue(veiwvalue);
        ngModelController.$render(); //change DOM
        if(veiwvalue.length === 10){
          return veiwvalue;
        }
      }