簡體   English   中英

當`ngModelChange`保持值時,Angular ngModel不會更新

[英]Angular ngModel doesn't update when `ngModelChange` keeps value

我有一個文本字段表示為: 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);
}

它的行為非常奇怪。

圖例: - 輸入:按下了什么鍵 - 更新前:第一個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"   |

為什么在輸入合法字符時它總是更新輸出? 它應該適用於每個事件調用。

編輯: Plunker

我認為原因是修改ngModelChange上的值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
}

如果有人在更新值時遇到問題,請在更新時使用setTimeout函數

// setTimeout function
setTimeout(() => {
  field.text = temp;
  this.cdRef.detectChanges();
}, 1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM