我正在尝试将用户输入重新格式化为输入的文本字段 . 例如,假设我想将输入限制为数字,并实现4个字符的maxLength,并在其前面加上显示的“”符号 .
我正在重新格式化IRL,但这应该是一个例子......
export class MyComponent {
private _myField: string;
myFieldDisplay: string;
onMyFieldDisplayChange(event) {
// I can see the display field has the correct value here
console.log(this.myFieldDisplay);
this._myField = event.replace(/\D/g, '').substring(0, 4);
this.myFieldDisplay = "+" + this._myField;
// and I can see the display field has the correct value here
console.log(this.myFieldDisplay);
}
}
这是我的模板代码:
<TextField
[ngModel]="myFieldDisplay"
(ngModelChange)="onMyFieldDisplayChange($event)">
</TextField>
我期望它将存储私有变量 _myField
,重新格式化 myFieldDisplay
并始终在TextField中显示重新格式化的 myFieldDisplay
值 .
会发生什么 - 我可以看到 myFieldDisplay
总是在控制台中正确地重新格式化,但这并不总是反映在TextField中 . TextField总是允许超过4个字符,并且它似乎只在第一次更改时去除非数字字符 . 即,如果输入的字符是非数字的,它仅在第一次按键时有效,有时仅有效 . 此外,"+"标志仍然可见 .
将 myFieldDisplay
日志记录到控制台是令人难以置信的,看它始终具有正确的值,但看不到反映在TextField中的值 .
我尝试过使用这个NativeScript Masked Input插件,但它没有像更严格的验证 .
是什么赋予了?有可能做我想做的事吗?有没有更简单的方法来实现这一点,我没有看到?
对于它的 Value ,我对NativeScript,TypeScript,Angular2和移动应用程序开发都很陌生......所以如果我遗漏了一些明显的东西,我不会感到惊讶 . 谢谢!
2 回答
你可以这样工作 -
HTML
TS
在这里,文本字段输入一旦达到10的文本长度就会得到子字符串 .
@Elleen Noonan在Angular-2中使用双向绑定需要导入FormsModule并且在NativeScript中更具体一点,你需要在相应的@NgModule中导入名为 NativeScriptFormsModule 的包装器
例如要使用this two-way binding,我们需要import the NativeScriptFormsModule here
关于双向绑定的更多信息here