Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 : trying to update ngModel with onModelChange inside the controller

I'm trying to update ngModel inside onModelChange

I know we can do something like that :

<input [ngModel]="myValue" (ngModelChange)="myValue = $event" />

But this is not what I'm looking for. I need to do some validation before updating myValue

Here is my code :

<input mdInput type="number" 
       [ngModel]="tax.refundAmount" 
       (ngModelChange)="onChange($event, tax.paidAmount)" />

And in the controller :

onChange($event, maxValue) {
    if ($event > maxValue) {
        $event = maxValue;
    }
}

But the ngModel is not updated :(

How can I update the model inside the controller ? The input shown up here is inside a ngFor loop so I cannot access the model directly

edit:

I tried with [(ngModel)] and (change) but there are timing problem when emiting the event to the parent controller

UPDATE 1

I want to do something inside the component class after updating the model, like emitting an event or computing values. Therefore I cannot return the value and then update the model in the template.

like image 815
Robouste Avatar asked Jun 28 '26 09:06

Robouste


1 Answers

Try this?

<input mdInput type="number" 
               [ngModel]="tax.refundAmount" 
               (ngModelChange)="tax.refundAmount = onChange($event, tax.paidAmount, tax.refundAmount)" />

And your controller:

onChange($event, maxValue, refundAmount) {
    return $event > maxValue ? maxValue : refundAmount;
}
like image 173
Arne Avatar answered Jun 30 '26 21:06

Arne