3

The keypress event is not fired in ionic 2 Android applications. The same is working fine with iOS and browser(chrome) platform. My requirement is to restrict the keyboard typing with some characters. ie, Don't want to show that characters which I typed in input field. The following code snippet as follows..

onKeyPress(event) {
    const pattern = /[0-9\.\ ]/;
    let inputChar = String.fromCharCode(event.charCode);
    if (!pattern.test(inputChar)) {
        event.preventDefault();
    }
}

:HTML

<input type="text" (click)="stopProcess()" (keypress)="onKeyPress($event)" />

The above function is not firing in android. Can anyone suggest me a solution for the same?

Sanu
  • 131
  • 1
  • 2
  • 8

1 Answers1

0

I usually use the JS key listener:

page.ts:

ionViewDidLoad() {
    document.addEventListener('keydown', (key) => {this.keydown(key)} );
}

keydown(key){
    console.log('Tadaaah')!
}

If you want to trigger events for each key, inside the function keydown(key), listen to the key.keyCode:

keydown(key){
  console.log(key.keyCode);
}

Press the keys you want to trigger the events, take notes and then add the functions:

keydown(key){
  if (key.keyCode == 13){
    this.functionA();
    return;
  }
  if (key.keyCode == 32){
    this.functionB();
    return;
  }
}

functionA() {
   console.log('Function A');
}

functionB() {
   console.log('Function B');
}

In summary

Your code should be like this:

  ionViewDidLoad() {
    document.addEventListener('keydown', (key) => {this.onKeyPress(key)} );
  }

  onKeyPress(key) {
    const pattern = /[0-9\.\ ]/;
    let inputChar: string = key.keyCode;
    if (!pattern.test(inputChar)) {
      event.preventDefault();
    }
  }
Caio Crespo
  • 93
  • 1
  • 6