Angular 2 - [(ngModel)] does not update after changing [value]

I set the input value by calculating the other two ngModels, and this seems to work fine. But if I check my ngModel, that will not 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 excellent. If I manually change this input, the changes will be reflected in the expression, which is fine too. But this input will be read-only, and it will be set by changing the other two inputs. When I change them, I see that the input value is updated just fine, but not the expression in the label. What is wrong there?

This is really strange because the value in the input GETS is UPDATED, but not the expression {{product.totalPrice}}, I think the value is updated because there are other fields, but these value changes never get into ngModel

By the way, I'm using Ionic 2

+4
source share
4 answers

In fact, it []means binding data and ()means emission changes / or allows you to pronounce an event with these changes from this user interface control <ion-input>. Thus, [()]does not mean two-way data binding. It means:

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

, .

+6

(ngModelChange) product.totalPrice. .

<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>
        (ngModelChange)="product.totalPrice = $event"
</ion-item>

<form> ngForm exportAs #someForm="ngForm", . - :

<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 }"
        name="totalPrice"
        #totalPrice="ngModel"></ion-input>
</ion-item>

, .

+2

, , , , , , , - .

, ngModel, ControlValueAccessor.

interface ControlValueAccessor {  
  writeValue(obj: any): void
  registerOnChange(fn: any): void
  registerOnTouched(fn: any): void
  setDisabledState(isDisabled: boolean): void
}

, , onChange, registerOnChange.

, onChange :

 onChange: any = () => { };
 registerOnChange(fn) {
   this.onChange = (obj) => fn(obj);
 }

- ,

this.onChange(this.value)

, .

+1

, . , , , . , :

[ngModel]="data.name" (ngModelChange)="testMethod($event)"

:

testMethod($event) {data.name = $event}

.

0

Source: https://habr.com/ru/post/1666557/


All Articles