【问题标题】:Input value not change along with ngModel update输入值不会随着 ngModel 更新而改变
【发布时间】:2023-03-08 02:37:01
【问题描述】:

我尝试修改输入中的文本以清除所有字母“a”。使用 ngModelChange,模型已更改,但输入中的值不会,直到我键入另一个有效字母。 我可以在更新模型后使用带有视图子喜欢input.value = this.testStr 的东西,但我想知道为什么输入中的值不遵循模型以及是否有更好的方法来处理它。

关注(ngModelChange) does not update the UI for specific input 的主题,我可以从使用ngModelChange 更改为(change) 事件,但这仅适用于输入模糊。我想在输入后立即更改输入值。我在更新this.testStr 后尝试使用ChangeDetectorRef,但它也不起作用。

【问题讨论】:

  • 你试过(input)="yourFunction()"
  • 是的,我有。模型发生了变化,但输入值仍然保持不变。例如:输入“1aaaaaa”,模型将是“1”,输入中的文本仍然是“1aaaaaa”,但是当你输入下一个“1”时,输入和模型都将是“11”。

标签: angular two-way-binding


【解决方案1】:

您还需要更改输入的“值”

<!--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。

见stackblitz

注意2:请不要在答案中附上带有代码的图像,最好编写代码(编写代码后选择它并使用 Ctrl+K 格式化)。更容易回答您的问题

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    相关资源
    最近更新 更多