Angular 2 component model refresh view without model changes

喜你入骨 提交于 2020-01-23 07:39:37

问题


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>

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).

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


回答1:


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
} 


来源:https://stackoverflow.com/questions/42281059/angular-2-component-model-refresh-view-without-model-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!