Performing addition in Angular 2 with the help of TypeScript

Here is a code snippet of a component I have written:

export class AppComponent {
    public num1: number = 2;
    public num2: number = 3;
    public sum: number = 0;
    public add() {
        this.sum = this.num1 + this.num2;
    }
}

However, when I run this code, instead of getting the correct sum of 5, I get 23. Can someone please provide me with a proper solution to fix this issue and achieve the correct addition result? Your help will be greatly appreciated!

Answer №1

Numbers are being treated as strings in this case, which is why you're seeing "2" + "3" = "23".

To convert them to numbers, you can use the parseInt function or do:

this.sum = +this.num1 + +this.num2;

Alternatively, this method should work as well:

this.sum = +this.num1 + this.num2;

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

initiate an animated sequence upon the initialization of the Angular server

Is there a way to launch a Netflix animation after my server has started without success using setTimeout? I don't want to share the lengthy HTML and CSS code. You can view the code for the animation in question by visiting: https://codepen.io/claudi ...

Securing your Angular application with an SSL certificate and key in the Ng Serve root directory

I am currently attempting to configure a SSL key and certificate on my ng serve using the following command: ng serve --ssl true --ssl-key './assets/somekey.key' --ssl-cert './assets/somecert.cert' However, when I run this command, th ...

Is it advisable to opt for window.webkitRequestAnimationFrame over setInterval?

Trying to figure out the best method for moving game characters in my JavaScript game - should I go with window.webkitRequestAnimationFrame or stick with setInterval? Any advice is appreciated! ...

Using Vue.Js to link a value to a checkbox within a component

I'm currently developing a custom component that wraps around a checkbox (similar to what I've done with text and number input types), but I'm facing an issue with binding the passed-in value correctly. Here's the structure of my compo ...

Global Redirect Pro is a cutting-edge redirection tool that

Check out the code below which successfully edits a link to redirect users to a specific website based on their location. I'm interested in enhancing this code in two ways: $(window).load(function () { $.getJSON('http://api.wipmania.com/json ...

Automatically Populate Text Field with the URL of the Current Page

I am hoping to automatically fill a hidden text field with the URL of the current page so that I can keep track of where form submissions are coming from. This simple solution will help me streamline my inquiry responses and save time. To clarify, upon lo ...

A Greasemonkey script for organizing and categorizing webpage elements

I've been working on a script to enhance the functionality of Facebook's find friends page by organizing suggested friends based on mutual connections. If you're interested in checking out the code, you can find it right here: http://pasteb ...

Is it possible to retrieve values from my model when working with Django Templates and incorporating them in the JavaScript header?

With Django, I have managed to successfully retrieve and display data from my model in the content section of the template. However, I am facing issues retrieving data from the model in the header section of the template. Below is the code --> view.py ...

Tips and tricks for setting up a functional react select component using Material UI

Having an issue with React Select material UI where the dropdown select is not functioning properly. The popup does not open up as expected. I am looking to display react select in a modal dialog box. import MenuItem from "@mui/material/MenuItem" ...

Encountering a Type Error while using Typescript in conjunction with React-Redux

I've been experimenting with react-redux and typescript, but I encountered a type error when using connect() and mapStateToProps to inject props. Here's how my component is structured: function mapStateToProps(state) { return { coun ...

Is there a way for me to personalize the background of the mui-material datagrid header?

I am looking to update the background design of Mui Datagrid from this image to this image However, I am encountering an issue where the background color does not fully cover the header. I have attempted using "cellClassName:" in the columns but it has n ...

What is the best way to incorporate the ability to strikethrough items in my task list?

I am currently working on a project to create a dynamic To-Do-List using Express and EJS. My goal is to implement a feature in the To-Do-List where checking a checkbox will cause the corresponding content to be striked-through. Initially, my approach invo ...

Mysterious line appearing beneath alternate rows in Table with border-collapse and border-spacing applied. Unable to pinpoint the culprit property causing the issue

After searching for a solution to add space between the rows in my table, I finally found the answer on Stack Overflow. The implementation seemed to work fine at first glance, but upon closer inspection, I noticed an issue depicted in the screenshot below: ...

Modify the names of the array variables

I am currently working with JSON data that consists of an array of blog categories, all represented by category id numbers. I am uncertain about how to create a new array that will translate these id numbers into their corresponding category names. Essen ...

The $.ajax request encounters an error when trying to parse the data as JSON

I am encountering an issue where my ajax call to a JSON file fails when using dataType: "json". However, changing it to "text" allows the ajax call to succeed. See the code snippet below: $.ajax({ type: "POST", url: url, dataType: "json", ...

The function argument does not have the property 'id'

I created a function that authorizes a user, which can return either a User object or a ResponseError Here is my function: async loginUser ({ commit }, data) { try { const user = await loginUser(data) commit('setUser', user) ...

Rearrange the arrangement of the array of objects

I am working with an array of objects that looks like this: [{ "Germany": "text", "Brazil": "50.00" }, { "Germany": "1000.00", "Brazil": "1100.00" }, { "Germany& ...

Can HTML5 and JavaScript be used to clip a portion of a video and upload it directly to a server?

Currently, I am using Filereader to read a local video file (mp4) in order to display it in a video tag. However, I am looking to cut a specific part of the mp4 file (for example, from 5 to 10 seconds) and then upload it to a server. My current approach: ...

Trim the name property of an object within an object's map function if it exceeds a certain length

Imagine having an object structured like this: var fullObj = { prop1: "myProp1", subobject: { Obj1_id: { id: "Obj3_id", name: "./", otherProperties:... }, Obj2_id: { id: "Obj2_id&q ...

Obtain the server-side cookie within the getServerSideProps function in Next.js

Attempting to implement authentication on my Next.js website. I've set up a signin endpoint at /api/users/signin where, upon verifying the user, a JWT token is generated and saved as follows: res.setHeader("Set-Cookie", `token=${token}; Htt ...