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.
Solution 1:
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) {...}
Solution 2:
@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)">