Angular 2组件模型刷新视图,无需更改模型 [英] Angular 2 component model refresh view without model changes

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

问题描述

我有一个正在使用Angular 2.4.0的应用程序,该应用程序具有某种形式的Java脚本来验证/格式化几个字段.字段的格式完成后,如果从格式返回的值与附加到模型的原始值匹配,则视图不会更新.有没有一种方法可以强制视图更新?由于没有模型更改,因此强制刷新组件没有任何效果.我猜想我需要用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组件模型刷新视图,无需更改模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆