【问题标题】:Validate input field on key press in Angular 2验证Angular 2中按键时的输入字段
【发布时间】:2017-07-29 00:11:34
【问题描述】:

我试图弄清楚如何在每次按键时验证输入字段。如果某些验证功能认为输入字段中的文本无效,我想取消按键或简单地恢复原始值。这样,输入字段应始终包含有效值。

所以输入字段如下所示:

<input [ngModel]="textValue" (ngModelChange)="onModelChange($event)" />

在我的组件中,我声明了一个 textValue 属性和一个处理 onModelChange 的函数:

onModelChange(newText: string) {
        if (checkText(newText)) {
            //input is valid, so update the model
            this.textValue = newText;
        }
        else {
            //cancel the keypress or restore the original value
            //HOW TO ACHIEVE THIS?
        }
    }

在尝试了很多数据绑定和处理按键事件的组合之后,我决定询问专家。提前致谢!

编辑: 我自己找到了解决方案。我没有处理 ngModelChange,而是订阅了输入事件,并使用 event.target.value 在每次按键时获取/设置适当的值。我的输入字段现在看起来像这样:

 <input [value]="textValue" (input)="onInput($event)" />

以及这里对应的onInput函数:

    onInput(event) {
            let newText: string = event.target.value;
            if (checkText(newText)) {
                //input is valid, so update the model
                this.textValue = newText;
            }
            else {
                //restore the original value
                event.target.value = this.textValue;
            }
        }

我希望这能帮助任何面临同样问题的人!

【问题讨论】:

    标签: angular


    【解决方案1】:

    您的解决方案还可以,但我也找到了替代方案

    <input ... (keypress)="validateKey($event)" >
    

    您可以使用keydown 和验证函数来代替keypress

    validateKey(event) {
      let oldval = event.target.value;
      let val = oldval.slice(0,event.target.selectionStart) + event.key + oldval.slice(event.target.selectionEnd);
    
      // here you have access to input oldval and (current) val
    
      if(val .... ) return true // allow to push charater
      return false              // not allow to push character
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2018-03-13
      • 2020-09-30
      • 1970-01-01
      • 2015-01-29
      • 2017-09-14
      • 1970-01-01
      相关资源
      最近更新 更多