【问题标题】:Angular7 - [ngModel] does not update in component, when typing in the same value twiceAngular7 - [ngModel] 不会在组件中更新,当两次输入相同的值时
【发布时间】:2019-06-02 14:24:39
【问题描述】:

最小的 Stackblitz 示例

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

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

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

这基本上是有效的:

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

但是 当我输入“test” - blur(它有效)并再次输入“test”时,它不再有效!

onInputUpdate() 函数被调用(您可以在控制台日志中看到它),变量 inputValue 被更新(您可以在组件 {{inputValue}} 中看到它),但是输入值不变! 我希望它是“测试编辑”,但它仍然是“测试”。

当我输入另一个字符串时它可以工作,但是连续输入相同的字符串 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)
  }
}

【问题讨论】:

  • updateOn 标志是否存在远离默认 change 的特定情况?
  • 尝试制作自己的 onFocus 来重置它? stackoverflow.com/questions/32019330/…
  • 我只希望值更新 onBlur,这就是为什么我设置了 ` [ngModelOptions]="{ updateOn: 'blur' }`

标签: angular angular-ngmodel angular-components angular7 angular-changedetection


【解决方案1】:

要确保在再次输入相同的值后更新输入字段,请通过调用 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 以获取演示。

【讨论】:

  • 完美!正是我希望它的行为方式。谢谢!
  • 这会起作用,但有人知道为什么双向绑定 [(ngModel)] 没有更新 inputValue 值吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多