Angular 2 - [(ngModel)] not updating after [value] changes

Agustín picture Agustín · Jan 11, 2017 · Viewed 62.1k times · Source

I'm setting the the value of an input calculating two other ngModels, and that seems to be working fine. But if I inspect my ngModel, it doesn't change at all. Let me show you:

<ion-item>
    <ion-label>Total price: {{product.totalPrice}}</ion-label>
    <ion-input 
        type="number"
        [value]="product.quantity * product.price"
        [(ngModel)]="product.totalPrice" 
        [ngModelOptions]="{ standalone: true }"></ion-input>
</ion-item>

So here {{product.totalPrice}} shows the initial value, which is fine. If I change manually that input, the changes will be reflected on the expression, that is also fine. But that input will be readonly and it will be set by changing two other inputs. When I change them, I see the value on the input is updating just fine, but not the expression in the label. What's wrong there?

It's really weird because the value in the input GETS UPDATED, but not the expression {{product.totalPrice}}, I guess the value is updating because the other fields are, but those value changes never actually hit the ngModel

By the way, I'm using Ionic 2

Answer

bunjeeb picture bunjeeb · Jan 11, 2017

Actually [] means bind data and () mean emit changes / or let say raise an event with these changes form this UI control <ion-input>. So [()] doesn't mean two way data binding. It means:

  • bind data using []
  • raise input changes ().

Check this example it shows many ways of binding data with input and how to raise changes.