3

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

Rager
  • 746
  • 4
  • 25

2 Answers2

4

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>
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54
  • Yes, I like this as well. Thanks – Rager Jun 05 '20 at 21:33
  • You're welcome and read this also to understand differance between change andngModelChange. Basically ngModelChange fire before bind change fire after bind. https://stackoverflow.com/questions/44840735/change-vs-ngmodelchange-in-angular – mr. pc_coder Jun 05 '20 at 21:37
3

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
}
HTN
  • 3,388
  • 1
  • 8
  • 18