当ngModelChange保持值时,Angular ngModel不会更新 [英] Angular ngModel doesn't update when `ngModelChange` keeps value

查看:77
本文介绍了当ngModelChange保持值时,Angular ngModel不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a text field represented as: field = {text: "", valid: false}, and an input with [(ngModel)]="field.text".

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

I want to make that field only accept a defined set of characters (for this issue, numbers), and doing (keypress) doesn't work on mobile, so I did: (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);
}

它的行为非常奇怪.

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

Legend: - input: what key was pressed - before update: first console.log - after update: second console.log - output: what I see on screen in the input

| 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"   |

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

Why does it always update the output when I enter a legal character? It should be working for each event call.

柱塞

推荐答案

我认为原因是修改 ngModelChange 上的值会中断更改检测,例如,如果您将值更改回前一个值,因为添加了无效字符.

I think the cause is that modifying the value on ngModelChange breaks change detection, for example if you change the value back to the previous value, because an invalid character was added.

解决方法:

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
}

这篇关于当ngModelChange保持值时,Angular ngModel不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆