Angular7 - [ngModel] 在两次输入相同的值时不会在组件中更新

Angular7 - [ngModel] does not update in component, when typing in the same value twice

最小 Stackblitz 示例

https://stackblitz.com/edit/angular-mqqvz1

在 Angular 7 应用程序中,我创建了一个带有 <input> 字段的简单组件。

当我用键盘更改输入值时,我希望该值被格式化 onBlur。 - 在最小的示例中,我只想向其中添加字符串 " EDIT"

这基本上是有效的:

不过 当我输入 "test" - blur(有效)并再次输入 "test" 时,它不再有效了!

onInputUpdate() 函数被调用(您可以在控制台日志中看到),变量 inputValue 被更新(您可以在组件 {{inputValue}} 中看到), 但是输入值没有改变! 我希望它是 "test EDIT",但它仍然是 "test"。

当我输入另一个字符串时它可以工作,但是连续输入同一个字符串 2 次却不起作用。这是为什么?我该如何解决这个问题?

component.html

{{inputValue}} <br />
<input type="text"
       [ngModel]="inputValue"
       (ngModelChange)="onInputUpdate($event)"
       [ngModelOptions]="{ updateOn: 'blur' }"/>

component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {

  inputValue = "teststring";

  constructor(
    private changeDetectorRef: ChangeDetectorRef,
  ) {}

  public ngOnInit() {
    this.inputValue = "initial";
  }

  public onInputUpdate(inputValue: string) {
    this.inputValue = inputValue + ' EDIT';
    this.changeDetectorRef.markForCheck();
    console.log('onInputUpdate new inputValue', this.inputValue)
  }
}

为确保输入字段在再次输入相同值后更新,通过调用 ChangeDetectorRef.detectChanges:

强制视图首先使用原始文本更新
public onInputUpdate(inputValue: string) {
  this.inputValue = inputValue;            // Set value to raw input text
  this.changeDetectorRef.detectChanges();  // Trigger change detection
  this.inputValue = inputValue + ' EDIT';
  this.changeDetectorRef.markForCheck();
}

有关演示,请参阅 this stackblitz