【发布时间】: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