Open In App

What is the difference between change and ngModelChange in Angular?

change: 
The change event is fired for <input>, <select>, and <textarea> elements when an alteration to the element’s value is committed by the user.The change event is not necessarily fired for each alteration to an element’s value. change is a DOM event that is it can trigger changes in HTML tags and elements. 
 




<label>Choose your favorite cartoon:
  <select class="cartoon" name="cartoon">
    <option value="">Select One …</option>
    <option value="Tom and Jerry">Tom and Jerry</option>
    <option value="Doraemon">Doraemon</option>
    <option value="Phineas and Ferb">Phineas and Ferb</option>
  </select>
</label>
  
<div class="result"></div>

Typescript file: 
 






const selectElement = document.querySelector('.cartoon');
  
selectElement.addEventListener('change', (event) => {
  const result = document.querySelector('.result');
  result.textContent = `You like ${event.target.value}`;
});

ngModelChange: 
When the user wants to change the model, by entering text into the input, the event callback fires and sets the new value to the model. We can’t use mgModelChange without ngModel because the ngModel class has update function with EventEmitter instance. ngModelChange will only be fired when the model will change or update.

<input [(ngModel)]="value" (ngModelChange)="function($e)">




<div style="color: red" *ngIf="isInvalid">
          Please check your ranges
</div>
<form (submit)="onSubmit()"
      id="inputForm"
      class="form-group" 
      class="row">
    <h3>Price Filters</h3>
    <span>Greater than:</span>
    <input type="number" name="greaterThanValue" 
         [(ngModel)]="greaterThanValue" 
         (ngModelChange)="onChange($event)" 
         placeholder="0">
    <span>Less than:</span>
    <input type="number" name="lessThanValue" 
         [(ngModel)]="lessThanValue" 
         (ngModelChange)="onChange($event)">
    <input type="submit">
</form>




import { Component } from '@angular/core';
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  
  public greaterThanValue = 0;
  public lessThanValue = 1;
  public isInvalid: boolean = false;
  
  public onChange(event: any): void {
    this.isInvalid =
     this.greaterThanValue > this.lessThanValue;
  }
}



Differences: 
 

change ngModelChange
change is bound to the HTML onchange event. It is a DOM event. ngModelChange is bound to the model variable binded to your input.
No such class is required. ngModelChange need ngModel class to function.
change event bound to classical input change event. ngModelChange It fires when the model changes. You cannot use this event without ngModel directive.
change triggers when the user changes the input. ngModelChange triggers when the model changes, irrespective of that change is caused by the user or not.

 


Article Tags :