简体   繁体   中英

ionic html input field of type number

Even though defining an input field as number still return as a string in the component

<ion-input [(ngModel)]="salary" 
      (ngModelChange)="calc($event)"
       required
      type="number" 
      name="salary">
</ion-input>

In the component as well the field is defined as a number

private salary: number;

Why does not it return as a number?

Thanks

This is a known issue .

As a workaround, you can use the ionChange event on the input to transform the value to a number, and then assign it to a class variable.

In your template

<ion-input [ngModel]="salary"
      (ionChange)="transform($event)"
      required
      type="number" 
      name="salary">
</ion-input>

In your component

transform(event) {
  // Multiply by 1 to transform to number
  this.salary = event.value * 1;
}

Another Work Around:

private salary: number;

Instead Of type number specify it as , string :

private salary: string;

Then let ion-input return string

cast it it integer or float according to your requirements like this:

parseInt(salary) 

if you cross check using typeOf it will give number .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM