Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 component model refresh view without model changes

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.

like image 658
Skeeterdrums Avatar asked Feb 16 '17 17:02

Skeeterdrums


1 Answers

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
} 
like image 175
Roman C Avatar answered Nov 13 '22 11:11

Roman C