I want to be able to add the numbers from two textbox:
template: `
<h1>Adding inputBox Numbers</h1>
<p>Num1: <input [(ngModel)]="num1"></p>
<p>Num2: <input [(ngModel)]="num2"></p>
<p>The sum is: {{ num1 + num2 }}</p> `
Even if I defined both variables as numbers:
export class AppComponent {
num1 : number;
num2 : number;
}
So if I perform this operation the result is OK
<p>The sum is: {{ 1 + 1 }}</p>
Result: 2
but if I use variables it preforms a concat so the result would be 11.
<p>The sum is: {{ num1 + num2 }}</p>
result:11
You can try this,
One way
<h1>Adding inputBox Numbers</h1>
<p>Num1: <input [(ngModel)]="num1"></p>
<p>Num2: <input [(ngModel)]="num2"></p>
<p>{{ num1*1 +num2*1 }}</p>
DEMO
2ND way
Create a function that will conver the String to a Number inside the ts file
ConvertToInt(val){
return parseInt(val);
}
then call it
<h1>Adding inputBox Numbers</h1>
<p>Num1: <input [(ngModel)]="num1"></p>
<p>Num2: <input [(ngModel)]="num2"></p>
<p>{{ ConvertToInt(num1) + ConvertToInt(num2) }}</p>
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With