[solved] Ngmodel input doesn't update when it's changed

Hello. I’m trying to allow user input only 2 decimal numbers after dot like (43.448 == 43.44) so I created an input with the ngModel and binded to ngModelChange function

<ion-input type="text" placeholder="100" [(ngModel)]="miktar" (ngModelChange)="onMiktarChange($event)" >
</ion-input>`
  miktar: String;
  onMiktarChange(num){
    var decimalCheck  = [];
    decimalCheck = num.toString().split('.');
    if(decimalCheck[1] !== undefined){
      decimalCheck[1] = decimalCheck[1].slice(0,2);
      num = decimalCheck[0] + '.' + decimalCheck[1];
      this.miktar = num;
      alert(this.miktar);
    }
  }

I create this.miktar as a variable and update it with the two digit decimal number when the user enters the third. This logic works fine. I get with alert(this.miktar);`` 44.54 like I want when I hit 44.546. But input doesn’t update and It shows me 44.546 . So I can’t prevent user to enter the third digit.

I think I need a different solution. Any ideas ? Thank you :’)

Try

(ionChange)

Instead of

(ngModelChange)

I tried (ionChange) but it doesn’t work. What is difference between them ?

Actually it may be

(ionInput)=“myFunction($event)” >

I haven’t actually used Ionic in a while. The difference is ionInput will fire on every change and will be current.

Ionic doesn’t always follow angular directives exactly. This is one of those times I believe.

Unless I’m misunderstanding your need, this should help.

try

(keyup)

or

(keydown)
1 Like

Try NgZone https://angular.io/api/core/NgZone

this.zone.run(()=>{
this.miktar = num;
});

this might be enough, or execute the whole onchange function in the Zone.

1 Like

I solved the issue with DecimalPipe and ChangeDetectorRef

onMiktarChange(num){
    this.cdRef.detectChanges();
    var decimalCheck  = [];
    decimalCheck = num.toString().split('.');
    if(decimalCheck[1] !== undefined){
      decimalCheck[1] = decimalCheck[1].slice(0,2);
      num = decimalCheck[0] + '.' + decimalCheck[1];
      this.miktar = num;
      return this.decimalPipe.transform(this.miktar, '1.1-2');
    }
  }

This worked for me. Thanks for all answers :’)

1 Like