How to fix NgModelChange Previous Value issue in Angular
if you ever have used an input, where on ngModelChange event you have a previous value inside a component, but not the current one, and you have no clue why? you came to the right place.
Exact Issue
suppose we have simple Angular application, with app-component
if you run this app and type letter “E”, the console will log undefined, after one more letter for example “R”, it will log “E”, after one more it will log the previous “ER” etc..
On the first hand, it looks quite normal yeah?, maybe Angular works this way that ngModelChange is fired before the value is sync from view-to-model, and you have to catch new value from $event parameter. but the craziest thing is that sometimes it has previous value, and sometimes it has the correct one, and that’s what drove me nuts, for a couple of months (It’s programming for god sake, it has to be deterministic one).
the only solution I found but had no clue how it worked, was to add setTimeout inside change() method, and the value was updated that time
setTimeout(()=>{console.log("Changed" , this.name);
})