Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 Adding two numbers view side

Tags:

angular

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> `

enter image description here

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

like image 713
Ale Garcia Avatar asked Aug 03 '17 11:08

Ale Garcia


1 Answers

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

like image 176
Sajeetharan Avatar answered Sep 23 '22 15:09

Sajeetharan