Angular2 ngModel change binding on Input type="number"

Rob picture Rob · Oct 13, 2016 · Viewed 11.7k times · Source

I have a number type input and when I try to change the value with an onChange event, it does not work.

I've tried the same for a text input and it works perfectly.

<input
   type="number"
   [(ngModel)]="element.value" 
   (change)="onChange($event)"
   >

export class NumFieldComponent {
    @Input() index;
    @Input() element; //element.value = 0

    onChange($event){

        var confirm = confirm("Are you sure about this?")

        if(confirm){
            //True, accept the value
        } else {
            this.element.value = 0;
            //Failed, set the input back to 0
        }
    }
}

I am new to Angular2 so what am I missing here?

PS. I have seen a similar issue with inputs that take bools

Answer

Lance picture Lance · Apr 23, 2018

changing to one-way binding worked for me, and it's cleaner not to fire the change if user cancels too (note I still had to manually update the DOM as you see):

<input
   type="number"
   [ngModel]="element.value"   // one way binding
   (change)="onChange($event)"
   >

export class NumFieldComponent {
    @Input() index;
    @Input() element; //element.value = 0

    onChange($event){

        var confirm = confirm("Are you sure about this?")

        if(confirm){
            this.element.value = $event.target.value
        } else {
            $event.target.value = 0;
            //Failed, set the input back to 0
        }
    }
}