当ngModelChange保持值时,Angular ngModel不会更新

Ami*_*mit 6 javascript angular

我有一个表示为的文本字段field = {text: "", valid: false},并带有的输入[(ngModel)]="field.text"

我想让该字段仅接受一组定义的字符(对于此问题,数字),并且(keypress)在移动设备上不起作用,所以我做到了:(ngModelChange)="fieldChanged(field)"

该方法执行以下操作:

fieldChanged(field) {
    console.log(field.text);
    field.text = Array.from(field.text).filter((char:string) => "0123456789".indexOf(char) != -1).join("");
    console.log(field.text);
}
Run Code Online (Sandbox Code Playgroud)

而且它的行为极其怪异。

图例:-输入:按下了什么键-更新之前:第一console.log -更新之后:第二console.log -输出:我在输入中在屏幕上看到的内容

| input   | before update | after update | output |
|---------|---------------|--------------|--------|
| ""      | ""            | ""           | ""     | <- starting position, no event
| "a"     | "a"           | ""           | "a"    |
| "a"     | "aa"          | ""           | "aa"   |
| "4"     | "aa4"         | "4"          | "4"    |
| "a"     | "4a"          | "4"          | "4a"   |
| "a"     | "4aa"         | "4"          | "4aa"  |
| "4"     | "4aa4"        | "44"         | "44"   |
Run Code Online (Sandbox Code Playgroud)

为什么在输入合法字符时总是更新输出?它应适用于每个事件调用。

编辑: 柱塞

Gün*_*uer 7

我认为原因是修改ngModelChange中断更改检测时的值,例如,如果您将值更改回先前的值,因为添加了无效字符。

解决方法:

constructor(private cdRef:ChangeDetectorRef) {}

fieldChanged(field) {
    console.log(field.text);
    field.text = Array.from(field.text).filter((char:string) => "0123456789".indexOf(char) != -1).join("");
    console.log(field.text);
    var tmp = field.text;
    field.text = null; // or some other value that normally won't ever be in `field.text`
    this.cdRef.detectChanges();
    field.text = tmp;
    this.cdRef.detectChanges(); // I guess this 2nd call won't be necessary
}
Run Code Online (Sandbox Code Playgroud)