Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ngModel change binding on Input type="number"

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

like image 346
Rob Avatar asked Nov 09 '22 07:11

Rob


1 Answers

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
        }
    }
}
like image 51
Lance Avatar answered Nov 15 '22 04:11

Lance