use arrow keys, with keyup in Angular

荒凉一梦 提交于 2020-01-29 09:36:26

问题


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);
    }


来源:https://stackoverflow.com/questions/47979846/use-arrow-keys-with-keyup-in-angular

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!