簡體   English   中英

輸入值不隨 ngModel 更新而改變

[英]Input value not change along with ngModel update

我嘗試修改輸入中的文本以清除所有字母“a”。 使用 ngModelChange,model 已更改,但輸入中的值只有在我鍵入另一個有效字母后才會更改。 在更新 model 之后,我可以使用視圖子喜歡input.value = this.testStr的東西,但我想知道為什么輸入中的值不遵循 model 以及是否有更好的方法來處理它。 在此處輸入圖像描述

按照(ngModelChange) 上的主題不更新特定輸入的 UI ,我可以從使用ngModelChange更改為(change)事件,但這僅適用於輸入模糊。 我想在鍵入后立即更改輸入值。 我在更新this.testStr后嘗試使用ChangeDetectorRef ,但它也不起作用。

您還需要更改輸入的“值”

<!--see that pass the input using a template reference variable-->
<input #input [ngModel]="testStr" 
              (ngModelChange)="validateInput($event,input)">

  validateInput(e: any, input: any = null) {
    const text = e.replace(/a/g, '');
    this.testStr = text;
    if (input.value != text) {
      const start = input.selectionStart - 1;
      input.value = text;
      input.selectionStart = input.selectionEnd = start;
    }
  }

注意:如果您在輸入的中間鍵入,則必須獲得 selectionStart。

查看堆棧閃電戰

注意2:請不要在答案中附上帶有代碼的圖像,最好是您編寫代碼(在編寫代碼后將其輸入 select 並使用 Ctrl+K 進行格式化)。 這讓回答您的問題變得更容易

暫無
暫無

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

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