3

I have a bunch of ionic 2 cards which I want to flip on the press of a key (any key, it doesn't matter). The code looks like

<ion-content padding>
    <ion-card (click)="setTime(7)" *ngIf="status == 'morning'" (keypress)="eventHandler($event)" style="width:80%">
        <img src="https://greatist.com/sites/default/files/Sleeping-Positions-feature.jpg"/>
    </ion-card>
</ion-content>

the .ts code

eventHandler(keyCode){
        alert('hey vikj');
  }

On pressing any key, my event handler is not fired.

Amr Eladawy
  • 4,193
  • 7
  • 34
  • 52
Vik
  • 8,721
  • 27
  • 83
  • 168
  • 1
    It's set up correct, but the focus needs to be on the ion-card before it starts to listen. Click on the card and then press a key and it should work. If you want the focus to be on the entire page check out this question: https://stackoverflow.com/questions/37362488/angular-2-listen-for-keypress-event-on-whole-page – Z. Bagley Jun 19 '17 at 18:23
  • 1
    keypress won't fire for all keys(example backspace) try with keyup or keydown – CharanRoot Jun 19 '17 at 18:27
  • 1
    @Z.Bagley if u post it as answer i can accept it as correct answer – Vik Jun 19 '17 at 19:45
  • Done, appreciate that. – Z. Bagley Jun 19 '17 at 21:53

2 Answers2

4

you can use this function in input field

(keypress)="onChange($event.keyCode)" 
Atif Hussain
  • 880
  • 12
  • 19
1

It's set up correct, but the focus needs to be on the ion-card before it starts to listen. Click on the card and then press a key and it should work. If you want the focus to be on the entire page check out this question: Angular 2 | listen for keypress event on whole page

Z. Bagley
  • 8,942
  • 1
  • 40
  • 52