本文介绍了没有模型更改的 Angular 2 组件模型刷新视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Angular 2.4.0 应用程序,我正在处理一个表单,该表单有一些支持 Javascript 验证/格式化几个字段.字段格式化完成后,如果格式化返回的值与附加到模型的原始值匹配,则视图不会更新.有没有办法强制视图更新?由于没有模型更改,因此强制刷新组件没有任何效果.我猜我需要用 jQuery 之类的东西单独更新视图,但我想先检查是否有更好的解决方案.

I have an Angular 2.4.0 application I'm working on with a form that has some backing Javascript validating/formatting a couple of the fields. When the formatting of the fields completes, the view does not update if the value returned from the formatting matches the original value attached to the model. Is there a way to force the view to update? Since there isn't a model change, forcing a component refresh hasn't had any effect. I'm guessing I'll need to update the view separately with something like jQuery, but I wanted to check if there was a better solution first.

组件:导出类组件{字段:字符串

Component: export class Component { field: string

  formatField(updatedField: string) {
    this.field = updatedField.replace(new Regexp("[^\\d]", "g"), ""); // remove everything except numbers
  }
}

HTML:

<html>
  <body>
    <input type="text" [ngModel]="field" (ngModelChange)="formatField($event)">
  </body>
</html>

在上面的例子中,如果模型是1",那么我输入"1;['];["formatField返回"1",屏幕仍会显示 "1;['];[" 当我希望 "1" 显示时(这是formatField 调用的返回值).

In the above example, if the model is "1", then I enter "1;['];[", and formatField returns "1", the screen will still display "1;['];[" when I'm expecting "1" to display instead (which is the returned value of the formatField call).

编辑:将示例中的 ngModelUpdate 固定为 ngModelChange(错别字).在描述中添加了 Angular 2 版本.

fixed ngModelUpdate to ngModelChange in example (typo). Added Angular 2 version to description.

推荐答案

要刷新视图,您需要在对模型进行更改后显式运行更改检测器,然后您可以修改模型和 ngModel 将更新值.

To refresh the view you need to explicitly run the change detector after you make a change to the model, then you can modify the model and ngModel will update the value.

constructor(private cd: ChangeDetectorRef) {}

formatField(updatedField: string) {
    this.field = updatedField;
    this.cd.detectChanges();
    this.field = updatedField.replace(new RegExp("[^\\d]", "g"), ""); // remove everything except numbers
}

这篇关于没有模型更改的 Angular 2 组件模型刷新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:30