Ionic 4中的(keypress)事件未能触发

10
根据此链接https://ionicframework.com/docs/api/input#events,Ionic支持keypress事件,该事件在浏览器中正常工作,但在移动设备上未触发。
<ion-item>
  <ion-label>Default Label</ion-label>
  <ion-input (keypress)="test($event)"></ion-input>
</ion-item>

ts

test(event){

console.log(event);
 e.preventDefault();
}

以上的代码在ionic serve环境下可以正常运行,但在移动设备上无法正常工作。

根据https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event,keypress事件已被弃用,我不理解。

我尝试过的事件有:keypress、keydown、keyup、ionblur、ionChange、input 等等。 它们要么不起作用,要么preventdefault不起作用。


面临相同的问题。 无论是 (ionInput) 还是 (keypress),都不起作用。 你找到让它工作的方法了吗? - mluis
3个回答

5

根据你提供的第一个链接,我猜你正在寻找事件ionInput 在键盘输入时触发。

<ion-item>
  <ion-label>Default Label</ion-label>
  <ion-input (ionInput)="test($event)"></ion-input>
</ion-item>

不要显示任何值,正如你所看到的,我已经给出了 event.preventDefault() - Mohan Gopi
event.preventDefault()ionInput 中不起作用吗?如果不起作用,我会尝试使用 @HostListner() 捕获键盘事件,但这可能不是最干净的方法。 - Gilsido

2
将$event传递给事件处理程序。$event是一个DOM KeyboardEvent。
<input type=text (keypress)="eventHandler($event)">

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

如果您知道需要哪个KeyboardEvent属性,可以将其传递到事件处理程序中:

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

eventHandler(keyCode) {...}

2
以上代码在浏览器中运行良好,正如我所提到的,在移动设备上无法触发。 - Mohan Gopi

0

使用@Gilsidoo答案中的readonly属性与ionInput事件,或其他事件如keyPress,在您的情况下可能有效。

<ion-item>
  <ion-label>Default Label</ion-label>
  <ion-input readonly (ionInput)="test($event)"></ion-input>
</ion-item>

编辑:我想使用readonly的onInput可能不起作用,可以尝试使用keyup。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接