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>
(keyup) is an Angular event binding to respond to any DOM event. It is a synchronous event that is triggered as the user is interacting with the text-based input controls. When a user presses and releases a key, the (keyup) event occurs.
The Complete Full-Stack JavaScript Course! To detect the arrow key when it is pressed, use onkeydown in JavaScript. The button has key code. As you know the left arrow key has the code 37. The up arrow key has the code 38 and right has the 39 and down has 40.
var leftKey = 37, upKey = 38, rightKey = 39, downKey = 40; var keystate; document. addEventListener("keydown", function (e) { keystate[e. keyCode] = true; }); document.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With