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

Mic*_*l B 5 angular-ngmodel angular-components angular angular-changedetection angular7

最小的Stackblitz示例

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

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

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

这基本上是有效的:

  • 如果我输入“ test”并模糊该字段,它将更改为“ test EDIT”
  • 如果我输入“ lala”并模糊该字段,它将更改为“ lala EDIT”

但是, 当我键入“测试”-模糊(有效)并再次键入“测试”时,它将不再起作用!

onInputUpdate()功能全被调用(你可以看到它在控制台日志),变量inputValue被更新(你可以看到它的组件{{inputValue}}),但是输入值不会改变! 我希望它是“测试编辑”,但它保持“测试”。

当我键入另一个字符串时,它可以工作,但是连续两次在同一字符串中输入却不起作用。这是为什么?我怎样才能解决这个问题?

component.html

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

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

Con*_*Fan 5

要确保在再次输入相同的值后更新输入字段,请通过调用强制视图首先使用原始文本更新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();
}
Run Code Online (Sandbox Code Playgroud)

有关演示,请参阅此 stackblitz