Issue
I am somewhat familiar with Angular and just got into Ionic Framework.
I’m facing a problem. I’m attempting to calculate (sum) two numbers given in the separate input fields and displaying the result below. Calculation works as expected if I input the numbers like: 1 or 1.0 but inputting 1. (no number given after the dot) returns null for that input field.
In template I have code as follows:
<b>1st input</b> <ion-input type="number" (ionChange)="calculate()" [(ngModel)]="firstInput"></ion-input>
<b>2nd input</b> <ion-input type="number" (ionChange)="calculate()" [(ngModel)]="secondInput"></ion-input>
<b>Total:</b> {{ total }}
And in component:
firstInput = null;
secondInput = null;
total = null;
...
calculate() {
this.total = this.firstInput + this.secondInput;
}
Why is null returned for 1. ? And is there a workaround to convert 1. into a number?
Solution
If you use normal inputs without type="number" and convert the values with Number() in the calculate function, you will get the right result:
<b>1st input</b> <input [(ngModel)]="firstInput" />
<b>2nd input</b> <input [(ngModel)]="secondInput" />
<button (click)="calculate()"></button>
<b>Total:</b> {{ total }}
firstInput = null;
secondInput = null;
total: number | null = null;
calculate() {
this.total = Number(this.firstInput) + Number(this.secondInput);
}
Answered By - eogabor
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.