Search code examples
javascriptangularinputtypescriptngmodel

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


Solution

  • Not tried but might work

    export class NumFieldComponent {
        @Input() index;
        @Input() element; //element.value = 0
    
        constructor(cdRef:ChangeDetectorRef) {}
    
        onChange($event){
    
            var confirm = confirm("Are you sure about this?")
    
            if(confirm){
                //True, accept the value
            } else {
                this.element.value = 0;
                this.cdRef.detectChanges(); // <<<=== added
                //Failed, set the input back to 0
            }
        }
    }