清除逗号按下的输入不会清除逗号 [英] Clearing an input on comma press doesn't clear the comma

查看:104
本文介绍了清除逗号按下的输入不会清除逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户按下逗号(,)时,我正在尝试清除输入。所以我做的是,在(按键)我会检查 keyCode 如果它是逗号我会清除通过将输入值设置为 input.value =''输入。

I'm trying to clear an input when a user presses comma (,). So what I did was, on (keypress) I would check the keyCode and if it's a comma I would clear the input by setting the input value to input.value = ''.

问题是即使它清除我输入的字母,它不清除逗号。我做错了什么?

The problem though is that even if it clears the letters I type in, it doesn't clear the comma. What am I doing wrong?

这是一个小提琴问题。

步骤:


  1. 输入 abc

  2. 输入

  3. 观察 abc 已清除,但输入仍然有

  1. Type in abc.
  2. Type ,
  3. Observe that abc was cleared but the input still has a ,.

HTML:

<input type="text" #elem (keypress)="clearInput($event)">

代码:

@ViewChild( 'elem' ) public element;

clearInput( e: KeyboardEvent ) {
 if ( e.keyCode === 44 ) {
    this.element.nativeElement.value = '';
 } else {
   console.log('Not a comma');
 }
}

我正在使用Angular 6。

I'm using Angular 6.

推荐答案


添加 preventDefault

clearInput 代码中添加 preventDefault(),如下所示:

Add preventDefault() in your clearInput code as shown below:

clearInput(e: KeyboardEvent) {
   if (e.keyCode === 44) {
      e.preventDefault();     // <-- Here
      this.element.nativeElement.value = '';
   } else {
      console.log('Not a comma');
   }
}

了解更多关于 preventDefault 的信息此处

这篇关于清除逗号按下的输入不会清除逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆