Search code examples
angular5nativescriptangular2-nativescript

angular 5, new model value has not been taken when model is changed using (ngModelChange)


In Angular 5, updated textbox value has not been taken in (ngModelChange). I have one text box which is used to enter the shipping cost, whenever the model is changed, I need to add with total cost and need to be displayed. Here, always take previous value instead of current entering value.

For example, previous it has 5, now, I am adding to 51, ngModel takes 5 only instead of 51 during the ngModelChange.

<TextField row="1" col="1" (ngModelChange)="sumOfRestocking();" [(ngModel)]="shippingFee" ></TextField>


sumOfRestocking () {
    console.log('shipping fee-->' + this.shippingFee);
// Takes only previous record, so I am not able to update the total correctly.
}

Anyone help me, why it takes previous value only instead of taking current value.


Solution

  • Pass the changes in to the function call

    <TextField row="1" col="1" (ngModelChange)="sumOfRestocking($event);" [(ngModel)]="shippingFee" ></TextField>
    
    
    sumOfRestocking (changes) {
        console.log('shipping fee-->' + changes);
    }
    

    ngModelChange fires as the model is changing, you can also use change for an up to date model but will fire on blur not keyup. You could use (keyup) as that will fire after the model has updated.

    <TextField row="1" col="1" (change)="sumOfRestocking();" [(ngModel)]="shippingFee" ></TextField>
    
    
    sumOfRestocking () {
        console.log('shipping fee-->' + this.shippingFee);
    }