简体   繁体   English

输入值不随 ngModel 更新而改变

[英]Input value not change along with ngModel update

I try to modify the text from the input to clear all letters 'a'.我尝试修改输入中的文本以清除所有字母“a”。 With ngModelChange, the model has been changed, but the value in the input would not until I type another valid letter.使用 ngModelChange,model 已更改,但输入中的值只有在我键入另一个有效字母后才会更改。 I can use something with view child likes input.value = this.testStr after update model, but I wonder why the value in the input does not follow the model and if any better ways to deal with that.在更新 model 之后,我可以使用视图子喜欢input.value = this.testStr的东西,但我想知道为什么输入中的值不遵循 model 以及是否有更好的方法来处理它。 在此处输入图像描述

Follow the topic at (ngModelChange) does not update the UI for specific input , I can change from using ngModelChange to (change) event, but that only work the input blurs.按照(ngModelChange) 上的主题不更新特定输入的 UI ,我可以从使用ngModelChange更改为(change)事件,但这仅适用于输入模糊。 I want to change the input value immediately after typing.我想在键入后立即更改输入值。 I tried with ChangeDetectorRef after updating this.testStr but it doesn't work also.我在更新this.testStr后尝试使用ChangeDetectorRef ,但它也不起作用。

you need also change the "value" of the input您还需要更改输入的“值”

<!--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;
    }
  }

NOTE: It's necessary get the selectionStart if you type in the middle of the input.注意:如果您在输入的中间键入,则必须获得 selectionStart。

See the stackblitz查看堆栈闪电战

NOTE2: please, don't attach image with code in an answer, it's better you write the code (after write code you select it and use Ctrl+K to formatter).注意2:请不要在答案中附上带有代码的图像,最好是您编写代码(在编写代码后将其输入 select 并使用 Ctrl+K 进行格式化)。 It's makes more easy respond your question这让回答您的问题变得更容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM