Sai Raman Kilambi
Sai Raman Kilambi

Reputation: 888

'+' is performing concatenation instead of addition in AngularJS

Here is my code where I am implementing a simple calculator in TypeScript .The problem here is that all the operations are working fine except addition where instead of addition, concatenation of numbers is performed.

HTML CODE :

<input type="text" [(ngModel)]="n1" />
 <input type="text" [(ngModel)]="n2" />

<h1>Number 1 : {{n1}}</h1>
<h1>Number 2 : {{n2}}</h1>

<select (change)="handle(selectField.value);" #selectField>
<option value="addition">Addition</option>
<option value="subtraction">Subtraction</option>
<option value="multiply">Multiplication</option>
<option value="divide">Division</option>

</select>


<h1>Result = {{result}}</h1>  

My Angular Code is as follows:

import {
  Component,
  OnInit
} from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  n1: number = 0;
  n2: number = 0;
  result: number = 0;

  handle(value: string) {

    if (value == "addition") {
      this.result = this.n1 + this.n2;
    } else if (value == "subtraction") {
      this.result = this.n1 - this.n2;
    } else if (value == "multiply") {
      this.result = this.n1 * this.n2;
    } else if (value == "divide") {
      this.result = this.n1 / this.n2;
    }

  }

  constructor() {}
  ngOnInit() {

  }

}

I have declared both n1 and n2 as numbers and also the result as number. So why is it that the numbers are being treated as strings instead of integers?

Note: I have gone through some other Stack Overflow posts on similar issue but couldn't find the possible solution.

Please help!

Upvotes: 0

Views: 2043

Answers (2)

MBielski
MBielski

Reputation: 6620

Any value from an HTML input is automatically string. To resolve this, you must cast/convert your input value to a number. The (+this.n1) hack does it, but to really do it right you should cast or convert your values.

this.result = parseInt(this.n1) + parseInt(this.n2);

This is just one way. There are several others.

Upvotes: 1

aimprogman
aimprogman

Reputation: 294

You can resolve it. this.result=(+this.n1)+(+this.n2);

Upvotes: 2

Related Questions