当我在 ngModelChange 中操作更新值时,未反映 ngModel 更新

ngModel update is not reflected when I manipulate the updated value in ngModelChange

这是我的 TS 和 HTML 个组件的文件:

<input type="text" [ngModel]="value" (ngModelChange)="setValue($event)">
value: string;

setValue(value: string) {
   const pattern = /[^0-9]/g;
   this.value = value.replace(pattern, '');
   console.log(this.value);  // <- When value is 123a, it puts 123 correctly
}

此处添加 Stackblitz:

https://stackblitz.com/edit/angular-ng-model-number


用于替换值中的任何非数字字母。但是输入元素没有更新。

所以如果我输入abcd,输入元素应该是空的,但它没有改变。

但是只要我输入一个数字,例如 abcd1,输入元素就会正确显示 1

但是,上面的 console.log 表明 this.value 已正确更新。

知道为什么会这样吗?


我试过使用 input 而不是 ngModelChange 但它是一样的。

<input type="text" [ngModel]="value" (input)="setValue($event.target.value)">

[新建]

我找到了正确的方法 (repo)。

首先,html 需要双向数据绑定 ngModel 属性。 然后监听 input 事件并在那里更改 ngModel 的值。

在将新值插入输入之前,首先检测其中的变化,然后然后设置新值。

<input type="text" #input [(ngModel)]="value" (input)="setValue(input.value)" />
constructor(private changeDetector: ChangeDetectorRef) {}

public setValue(value: string) {
  const parsedValue = value || "";
  this.changeDetector.detectChanges();
  this.value = parsedValue.replace(this.pattern, "");
}
  

[旧回复,使用 ReachtiveForms]

我会说

我已经使用 reactive forms 方法重现了您的案例,效果很好。

https://stackblitz.com/edit/angular-ng-model-number-ppqajh?file=src/app/app.module.ts