Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular [(ngModel)] changing data after other events fire

I'm not an expert on Angular events but here's my issue. If I run the following code I'm bassically updating the backend with the wrong information because item.their_platform doesn't change before togglePlatform() fires.

Template:

<mat-checkbox (ngModelChange)="togglePlatform()" [(ngModel)]="item.their_platform"></mat-checkbox>

TS:

 togglePlatform(){
      //update backend with the new value for item.their_platform
  }

I've solved the issue by using a timeout in the togglePlatform method, though I'm hoping there's a different event I can tie that method to that makes more sense in this scenario.

Is there a better event? Is this a side effect of using mat-checkbox vs using vanilla Angular?

Thanks

like image 866
Rager Avatar asked Mar 31 '26 03:03

Rager


2 Answers

you can use change rather than ngModelChange. Because change fires after binding , ngModelChange fires before binding.

<mat-checkbox (change)="togglePlatform()" [(ngModel)]="item.their_platform"></mat-checkbox>
like image 166
mr. pc_coder Avatar answered Apr 02 '26 19:04

mr. pc_coder


Do not rely on the order the execution as you are not always which arrives before. In your case, solution should be:

<mat-checkbox (ngModelChange)="togglePlatform($event)" [(ngModel)]="item.their_platform"></mat-checkbox>
togglePlatform(value) {
     // update backend with the value, not item.their_platform
}
like image 34
HTN Avatar answered Apr 02 '26 18:04

HTN