use arrow keys, with keyup in Angular

2020-03-05 02:50发布

问题:

I have an Angular project, and I want to implement some functions to arrow keys, I tried to use something like (keyup.[keyCode])="Move(itemArray, 'UP') _where [keyCode] represents the code of one of arrow keys_But nothing works, here's the template where I use this.

The Template (HTML)

 <div (keyup.38)="Move(itemArray, 'UP')"
     (keyup.37)="Move(itemArray, 'LEFT')"
     (keyup.40)="Move(itemArray, 'DOWN')"
     (keyup.39)="Move(itemArray, 'RIGHT')">
  <div>
    <div class="score">
      <span>Best:</span>
      {{best}}
    </div>
    <div class="score">
      <span>Score:</span>
      {{score}}
    </div>
  </div> <br>
  <div class="game-container">
    <div class="grid-container">
      <div *ngFor="let item of itemArray">
        <div class="grid-cell-{{item.level|number}}">
          <span>{{item.level}}</span>
        </div>
      </div>
    </div>
  </div>
  <div class="button-container">
    <div>
      <button class="empty"></button>
    </div>
    <div>
      <button class="control-button" (click)="Move(itemArray, 'UP')">Up</button>
    </div>
    <div>
      <button class="empty"></button>
    </div>
    <div>
      <button class="control-button" (click)="Move(itemArray, 'LEFT')">Left</button>
    </div>
    <div>
      <button class="control-button" (click)="Move(itemArray, 'DOWN')">Down</button>
    </div>
    <div>
      <button class="control-button" (click)="Move(itemArray, 'RIGHT')">Right</button>
    </div>
  </div>
</div>

回答1:

Exploring Angular's relevant pull request, it created the impression that this feature does not support key codes, but only a set of key names.

(keyup.arrowup)="Move(itemArray, 'UP')"
(keyup.arrowleft)="Move(itemArray, 'LEFT')"
(keyup.arrowdown)="Move(itemArray, 'DOWN')"
(keyup.arrowright)="Move(itemArray, 'RIGHT')"

Notice the usage of names instead of numbers.



回答2:

If you just want to get the key typed, you can do:

   <button class="control-button" (keydown)="move($event)"></button>

    move(event: any) {
         console.log(event.keyCode);
    }