Will ngModel binding always precede change event?

Viewed 612

In the following example, the textbox has an associated ngModel binding as well a change function:

<input type="text" [(ngModel)] = "typedText" (change)="calculateTextLength()" />

In my limited experience, the "calculateTextLength()" function is called only after the input text has been updated in the "typedText" variable.

Can I know if there is a precedence order for these?

2 Answers

To explain the process here, we should take some notes:

  • change is not an “Angular event”, it’s a DOM event.
  • We can use change anywhere (not linked to Angular system).
  • change will be fired when the user has blurred (~leave) the input (we are talking about DOM here not Angular)
  • In Angular, and although it is not required to use change with ngModel in the same element (which not the case for Angular's ngModelChange), if we use them both, it will fire after the value bound to [(ngModel)] has changed

  • There's an angularized version of change which is ngModelChange: an Angular event, it fires when (before) ngModel changes.
  • We cannot user ngModelChange without ngModel (not the case for change)
  • ngModelChange will only fire when the model is intended to be updated, i.e. essentially it is listening to the input event, and setting the model if a user types, pastes or changes the input’s value, that means : will be fired before the value bound to [(ngModel)] has changed.

Src & More details.

First we need to understand that (change) is not an “Angular event”, it’s a DOM event.If you want dynamic binding you can use event called (ngModelChange) instead of (change).I think that this should solve the issue.The order of attributes inside the tags doesn't matter but you can always rearrange them for better ease of understanding

Related