Robson
Robson

Reputation: 1277

How can I get pressed key from ng2 app?

I have a problem with getting pressed key in my simple ng2 app.

I just want to check everytime which key was pressed.

I created markup with focused input with keyup event for getting which key(letter) is pressed:

<input type="text" class="input-letter" id="input-letter" #box (keyup)="onKey(box.value)">
<div>
    {{key}}
</div>

It works, but I want to get single key value everytime, and clear current key value, at the moment all keys/letters are appending to key variable.

I tried to use method like clearKey() below, but it's not working.

clearKey(): void{
    this.key = null; // I tried to use ' ' instead null
}

onKey(value: string): void {
    this.clearKey();
    this.key = value;      
}

Thanks for any suggestions what I'm doing wrong.

Upvotes: 0

Views: 39

Answers (1)

helllomatt
helllomatt

Reputation: 1339

Pass the keyboard event to the onKey function, instead of the input value.

<input type="text" class="input-letter" id="input-letter" #box (keyup)="onKey($event)">
<div>
    {{key}}
</div>

Then

onKey(e: KeyboardEvent): void {
    this.clearKey();
    this.key = e.key;      
}

Upvotes: 2

Related Questions