August 6, 2020

Difference between angular change and ngModelChange

while developing an angular application, You might have come into the situation where you need to handle change events for particular input then you might be confused with which one to use either change or ngModelChange.

let’s simplify the situation for you.

(change)=”callback($event)” is a addEventListner(‘change’,callback) .It just registered with angular and it doesnt need ngModel to fire.

(ngModelChange)=”callback($event)” is associated with ngModel directive. If ngModel value changes then ngModelChange event fires.

let’s understand both the event listner in Details

(change) event

As I said change event listen to the DOM event

for eg.

<input type="text" (change)="changeEvent($event)" />

what we type in the input box can be accessiblle using event.target.value.

You can’t get value directly. Please refer below example

changeEvent(event) {
    console.log(event.target.value)
  }

In the above example as we can see we don’t need ngModel to fire to change event. above code is exactly same as

<input id="textInput" type="text" />
var input = document.getElementById('textInput');
 input.addEventListener("change", function(event) {});

why we have (change) emitter? because first, it gives syntactic sugar to use addEventListner on your element

The other one is if you do any changes in addEventListner callback which considers outside the angular zone, where don’t know about the changes done, so angular will not run change cycle to update the view. In the case of (change) you don’t need to worry about angular update cycle

(ngModelChange) event

ngModelChange event doesn’t come independently.It comes with ngModel directive. and ngModelChange emits only when ngModel value changes.

As you can see ngModel implementation in angular github project

/**
   * @description
   * Event emitter for producing the `ngModelChange` event after
   * the view model updates.
   */
  @Output('ngModelChange') update = new EventEmitter();

It says that this output event will fire when the model changes

as you can see below angular library code

/**
   * @description
   * Sets the new value for the view model and emits an `ngModelChange` event.
   *
   * @param newValue The new value emitted by `ngModelChange`.
   */
  viewToModelUpdate(newValue: any): void {
    this.viewModel = newValue;
    this.update.emit(newValue);
  }

this is one of the function where emitting ngModelChange event.

ngModelChange direct gives value as output in callback not like change event.

you can check this example on stackblitz to understand

Conclusion:

Both change and ngModelChange can be used for the same purpose but change function will give you DOM object and ngModelChange will give you entered value into the field

If you like this example please share it and follow me on twitter

Leave a Reply

Your email address will not be published. Required fields are marked *