Sequential order of ngModel and ngModelChange, problem or not!

As you start newly with angular, ngModel and ngModelChange are the things you probably try to implement and check first.

ngModel is a directive which binds input type controls (select, textarea), and stores the required user value in a variable and we can use that variable whenever we require that value. whereas ngModelChange is the @Output of ngModel directive. It fires when the model changes.

You cannot use this event without ngModel directive. and when you do some changes in the view, you expect you will get the latest model changes in the listener function you have configured on modelChange. Well it don't work always. It's returning previous value every single time.
Check this following code snippet carefully. Both looks same. Only difference is the sequence in which (ngModelChange) and [(ngModel)] are placed.

 <h1>ganeshk4</h1>
<select (ngModelChange)="onSelection()" [(ngModel)]="selectedOption">
  <option *ngFor="let option of this.options" [value]="option">{{option}}</option>
</select>

<select [(ngModel)]="selectedOption2" (ngModelChange)="onSelection2()">
  <option *ngFor="let option of this.options" [value]="option">{{option}}</option>
</select>

Here is the component code for it.

export class AppComponent  {
  name = 'Angular 5';
  selectedOption: string;
  selectedOption2: string;
  options = ['node1','node2'];

 onSelection(){
   console.log(this.selectedOption);
 }

 onSelection2(){
   console.log(this.selectedOption2);
 }
}

This is how the similar looking dropdown works.




The second one is posting actual value which we expect, and the first one always posts previous value. Some how these are behaving as afterModelchange and beforeModelChnage. Take a look at the GIF below. Suprising isn't it. Its because the sequence in which we use these two attributes, matters. And always use ngModel before ngModelChange.

Happy coding.

You can also check their working here.

Comments

Popular posts from this blog