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

编程入门 行业动态 更新时间:2024-10-21 11:59:30
本文介绍了当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不会更新

本文发布于:2023-11-11 23:24:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579827.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ngModelChange   Angular   ngModel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!