TheFisherman
TheFisherman

Reputation: 1279

Get which key pressed from (keypress) angular2

Is it possible to find out which key was pressed when using (keypress) in Angular 2?

E.g.

<input type=text (keypress)=eventHandler()/>

public eventHandler() {
    //Some code
    console.log(keyPressed);
}

Edit: Seems my naming conventions were a bit off. I did not mean AngularJS 2, I meant Angular 2.0 with typescript.

Upvotes: 51

Views: 108776

Answers (4)

ben marder
ben marder

Reputation: 103

2020 Update:

event.keyCode is deprecated and you should use event.code instead (just check for browser compatibility first)

<input type=text (keypress)="eventHandler($event)">

eventHandler(event: KeyboardEvent) {
   console.log('Key pressed is:', event.code);
}

Deprecation of event.keyCode:

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

event.code browser compatibility:

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code#Browser_compatibility

Upvotes: 1

Emeka Obianom
Emeka Obianom

Reputation: 1794

Based on the comment made on the answer:

this does not detect all events. for example not arrow keys or escape. but you can use (keydown) to get all of them.

The best solution to get all events both backspace and delete or whatever key, just use (input)

<input type=text (input)="eventHandler($event.keyCode)">

eventHandler(keyCode) {...}

Upvotes: 5

Clayton K. N. Passos
Clayton K. N. Passos

Reputation: 1362

@Component({
  selector: 'key-up3',
  template: `
    <input #box (keyup.enter)="onEnter(box.value)">
    <p>{{value}}</p>
  `
})
export class KeyUpComponent_v3 {
  value = '';
  onEnter(value: string) { this.value = value; }
}

Or use like this..

 <input #box (keyup.enter)="onSubmit(form.value)">
 <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)">

Upvotes: 19

Mark Rajcok
Mark Rajcok

Reputation: 364677

Pass $event to your event handler. The $event is a DOM KeyboardEvent.

<input type=text (keypress)="eventHandler($event)">

eventHandler(event) {
   console.log(event, event.keyCode, event.keyIdentifier);
} 

If you know which KeyboardEvent property you want, you can pass that into your event handler:

<input type=text (keypress)="eventHandler($event.keyCode)">

eventHandler(keyCode) {...}

Upvotes: 92

Related Questions