In AngularJS, the use of the '+' operator is causing concatenation instead of addition

Looking for assistance with my TypeScript code where I've created a basic calculator. Everything is working as expected except for addition, which seems to be concatenating the numbers instead of adding them together.

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 defined variables n1 and n2 as numbers in my TypeScript code, along with the result variable. However, it seems that the numbers are being treated as strings rather than integers during operations. Any idea why this might be happening?

Note: I have searched through various posts on Stack Overflow but haven't found a solution yet. Your help would be greatly appreciated!

Answer №1

You have the ability to solve it. Let this solution be equal to the sum of n1 and n2.

Answer №2

When retrieving a value from an HTML input, it is important to remember that it will be stored as a string by default. To ensure accurate calculations, you should convert or cast the input values to numbers. One common approach is using the (+this.n1) hack, but for more precise results, it is recommended to properly convert or cast the values.

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

Keep in mind that this is just one method, as there are various other techniques available.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Element Ui component fails to update when the prop of the Vue component changes

In my project, I have a parent component and several child components which all make use of the same prop. This prop is an array of keys that are used for a dropdown menu in element.js. Initially, when the children render for the first time, they do not co ...

Creating a Modal in React without the need for a button to trigger it

I am working on implementing a model using the React Material UI library to display information on the landing page when a user logs in. However, I am facing an issue with closing the modal once it appears despite using a timeout trigger. const[post,setP ...

Encountering an issue while fetching data from the server - Unable to access properties of undefined (specifically 'toString')

I have encountered an issue where I am trying to set the default value of a select element to the data received from the server. Despite knowing that user.roleId is not undefined, I am getting an error specifically with the select element. Other input elem ...

Mastering the art of completing a form using AJAX

I'm working on a checkbox that triggers AJAX to create a new log. It populates the necessary information and automatically clicks the "create" button. However, I'm facing an issue where the hour value is not changing. Any help on what I might be ...

Utilizing classes as types in TypeScript

Why is it possible to use a class as a type in TypeScript, like word: Word in the provided code snippet? class Dict { private words: Words = {}; // I am curious about this specific line add(word: Word) { if (!this.words[word.term]) { this.wor ...

The ThemeProvider does not automatically provide theme injections

After creating a theme using the createTheme method from @mui/material/styles, I attempted to apply this theme using ThemeProvider from the same package. This snippet showcases the dark theme that was created: export const darkTheme = createTheme({ pale ...

Loading JavaScript asynchronously using ExtJS

I have created a custom widget using the ExtJS framework. In order to load the necessary ext-all.js script asynchronously, I wrote an embedd.js script that also combines other JavaScript files. I've attached a function to be called when Ext.onReady is ...

What is the most effective way to extract the value of a "$3" element using Selenium in Python?

I am facing a challenge in fetching an element from the netlify dashboard. The code I have currently grabs the base element that the web developers have set, indicating that it gets updated with javascript. However, I am having trouble accessing this updat ...

Clicking the button will trigger the onclick event

I'm working on a button component in TypeScript and I have encountered an issue with passing the event to the submitButton function. import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: Reac ...

Modifying the user interface (UI) through the storage of data in a class variable has proven to be

If I need to update my UI, I can directly pass the data like this: Using HTML Template <li *ngFor="let post of posts; let i = index;"> {{i+1}}) {{post.name}} <button (click)="editCategory(post)" class="btn btn-danger btn-sm">Edit</butto ...

Why does json_encode() work for one string and fail for another?

UPDATE: Resolved the issue. Initially, someone left a comment with a solution that was later deleted. Interestingly, simply adding semi-colons after the two json_encode lines fixed the problem. I'm still puzzled as to why string1 worked without a clo ...

How to iterate dynamically over arrays using JavaScript

I am working on a JavaScript project where I need to create a graph with 25 different data points. While my current JavaScript method is effective, I am facing an issue - I have multiple arrays and I am looking for a solution that allows me to use a for lo ...

Steps for generating instances of an HTML page and dynamically adding them to a list on the main page

I have a main HTML page and I need to insert a dynamically generated list from a template in another HTML file that I created. The template for each item in the list is located on a separate HTML page. My goal is to create multiple instances of this HTML ...

Encountering Datepicker Issue in Your Angularjs App?

I am currently working on a web application using Angular JS and I encountered an error when trying to incorporate a date picker. The error message displayed is "elem.datepicker is not a function" To implement the datepicker, I found reference code in thi ...

MUI: The value you have chosen for the select component is outside the acceptable range - `[object Object]`

I'm currently in the process of developing a custom Select component that offers both single and multi-selection features. Below is how I initialize the components: const vendorList = [ { label: "John", value: "668", } ...

The error message that occurs when using angularjs $scope.$apply() is: Error: [$rootScope:inprog]

Having trouble updating text on a page within the $scope. Facing this error message: Error: [$rootScope:inprog] [http://errors.angularjs.org/1.2.15/$rootScope/inprog?p0=%24apply] at Error (native) at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/ ...

Utilizing Angular 2 and appengine with Python to successfully pass a basic GET request

I am currently attempting to run Angular 2 on the front end and App Engine Python on the back end. To achieve this, I have launched the App Engine Python backend server using dev_appserver.py --port 3030 app.yaml, and the Angular 2 frontend server using "n ...

Proper method for incorporating a single database pool across an Express application

Disclaimer: This issue pertains to singleton objects in Node.js and not DB pools. While developing an Express.js application with the mysqljs node module for DB connections, I am interested in creating a single pool object that can be reused across differ ...

This as well as its parent node

I am looking to implement a function where an element is manipulated if a child of it is clicked (by adding a CSS class to it). My current approach is as follows: function mahlzeitRaus() { console.log("Out"); //this.className += " not"; this. ...

Switch between two fields using just one animation

I've been experimenting with creating an information tag that slides out from behind a circular picture. To achieve this effect, I created a block and circle to serve as the information field placed behind the image. However, I'm facing a challe ...