Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 963
TheFisherman Avatar asked Dec 08 '15 13:12

TheFisherman


People also ask

How do you check if a specific key is pressed?

The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed.

What is e keycode === 13?

Keycode 13 is the Enter key.

How do I get a keypress event?

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .

Should I use keypress or Keydown?

The keypress ignores keys such as delete , arrows , page up , page down , home , end , ctrl , alt , shift , esc , etc. So, if we need to handle those keys, it's better to use either keydown or keyup event. }); The keydown and keypress events fire multiple times if user press and hold a key.


2 Answers

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) {...} 
like image 151
Mark Rajcok Avatar answered Oct 03 '22 20:10

Mark Rajcok


@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)"> 
like image 34
Clayton K. N. Passos Avatar answered Oct 03 '22 19:10

Clayton K. N. Passos