用户输入时更新输入时遇到问题。
我需要从用户那里获得一个类似于以下代码:354e-fab4(由4个字符组成的2个字母数字组,用'-'分隔)。用户不应键入“-”,它会自动插入。 当用户键入的内容与用于验证的正则表达式不匹配时,我想恢复为先前的有效值。
问题是验证失败时输入中的值未正确更新。另一方面,如果我设置了一个硬编码的字符串,则该值将反映在输入中。
我以堆栈闪电的方式隔离了该问题:https://stackblitz.com/edit/angular-qsbtiz
您可以通过键入8个以上的字符来重现该问题:regexp测试失败,代码设置为先前的值,但是该值未反映在HTML输入中。
这是输入值更改时需要的方法:
onCodeChange(newValue: string) {
const previousValue = this.code;
this.code = newValue;
const regex = new RegExp(/^([a-z0-9]{0,4})?(-)?([a-z0-9]{0,4})?(-)?$/);
// If the code doesn't match the regex, revert to the old value and return.
if (!regex.test(newValue)) {
// This changes this.code, but it's not reflected in the input's value.
this.code = previousValue;
// This changes this.code and it is reflected in the input's value.
//this.code = '1234';
} else {
const groups = regex.exec(newValue);
if (!groups[2] && groups[3]) {
this.code = `${groups[1]}-${groups[3]}`;
}
}
}
请注意,我对这段代码的问题感兴趣,而不是对其他替代解决方案(如使用自定义蒙版输入组件)感兴趣。
谢谢。
答案 0 :(得分:2)
由于您拆分了[(ngModel)]
。我建议通过将自身的元素传递给onCodeChange()
函数来进行设置:
Stackbliz example
在模板中:
<input #input type="text" placeholder="" (ngModelChange)="onCodeChange($event,input)" [ngModel]="code"/>
在您的TS文件中:
code = '';
previousValue = ''
onCodeChange(newValue: string, input) {
this.code = newValue;
const regex = new RegExp(/^([a-z0-9]{0,4})?(-)?([a-z0-9]{0,4})?(-)?$/);
if (!regex.test(newValue)) {
console.log("No match. Reverting the code to the previous value (this is not working as expected).");
input.value = this.previousValue;
} else {
const groups = regex.exec(newValue);
if (!groups[2] && groups[3]) {
this.code = `${groups[1]}-${groups[3]}`;
}
//Save previousValue here instead
this.previousValue = this.code
}
}
答案 1 :(得分:0)
如果要恢复以前的值,则应声明previousValue
并分配这样的值。
https://stackblitz.com/edit/angular-vdqbxz
我将onModelchange
事件更改为keyup
,因为这些组由于某种原因(IMO与该帖子无关)而无法正确生成。