0

Angular typescript concatenating numbers instead of adding

Class

  title = 'app';

  a: number;
  b: number;

  c: number;

  calc(): void {
    this.c = this.a + this.b;
  }

View

<input type="text" [(ngModel)]="a" (keyup)="calc()">
<input type="text" [(ngModel)]="b" (keyup)="calc()">

<p>{{c}}</p>

Return

if a = 1 and b = 2 for example it equal c = 12, it should be 3 and when i try parseInt(this.a) it result error Argument of type 'number' is not assignable to parameter of type 'string'.

2
  • 1
    I think the problem is that you declare the properties as number, then what the typescript is saying make sense. Changing the type to string should solve that issue. Commented Jul 22, 2020 at 4:48
  • use the "+" to convert in number: this.c=(+this.a)+(+this.b) Commented Jul 22, 2020 at 6:25

4 Answers 4

1

The problem is that in the input type you have mentioend the type as text. Change it to number and it should work fine.

<input type="number" [(ngModel)]="a" (keyup)="calc()">
<input type="number" [(ngModel)]="b" (keyup)="calc()">

<p>{{c}}</p>

Also in the ts file initialize the values of a and b to 0, else you will see a NaN error while giving in input.

a: number =0;
  b: number=0;

Sign up to request clarification or add additional context in comments.

1 Comment

how is that happen angular should respect typescript rules ( variables types ) and parsed to number in background. because when i change type to number template design and css selectors will change also.
1

use the "+" to convert in number. In Angular, by defect, the input in an ngModel is a string

this.c=(+this.a)+(+this.b)

NOTE: you can use directly in the .html

{{+a+(+b)}}

Comments

0

You can't use parseInt over number field, because it's already number.(However compiler thinks so). But when you bind it to input with type text, it'll be converted into string. If you want to input only numbers you should use

<input type='number'>

This is how angular model binding works.

2 Comments

how is that happen angular should respect typescript rules ( variables types ) and parsed to number in background. because when i change type to number template design and css selectors will change also.
Yes, typescript respects variable types. But in runtime it's not typescript anymore, it's javascript.
0

Try like this

calc(): void {
    this.c = this.a + '' + this.b;
  }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.