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?
CodePudding user response:
Change the {total} you have to rather just saying {input1 input 2} And just make sure they are of type number, otherwise just convert them to one
{Number(input1) Number(input2)}
CodePudding user response:
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);
}