Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...