Gareth Oates
Gareth Oates

Reputation: 397

Angular2: + operator converting number types to strings

Can anyone explain why the '+' operator in my binding is concatenating my variables as strings, whereas other arithmetic operators such as -, * and / are correctly doing the arithmetic operations on them as numbers, which is their type in the associated typescript file.

Contents of voter.component.html

<i class="glyphicon glyphicon-menu-up"
(click)="UpVote()"
[class.highlighted]="myVote === 1"></i>

<span class="vote-count">{{ voteCount + myVote }}</span>

<i class="glyphicon glyphicon-menu-down"
(click)="DownVote()"
[class.highlighted]="myVote === -1"></i>

Contents of voter.component.ts

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

@Component({
    moduleId: module.id,
    selector: 'ui-voter',
    templateUrl: './voter.component.html',
    styleUrls: ['./voter.component.css']
})
export class VoterComponent {

    @Input() voteCount: number;
    @Input() myVote: number;

    UpVote() {
        if (this.myVote === 1) { return; };
            this.myVote++;
    }

    DownVote() {
        if (this.myVote === -1) { return; };
            this.myVote--;
    }
}

The line in my app.component.html file which uses this component

<ui-voter voteCount="20" myVote="0"></ui-voter>

Upvotes: 1

Views: 704

Answers (1)

Stefan Svrkota
Stefan Svrkota

Reputation: 50643

Remove quotes, voteCount and myVote are interpreted as string when you use double quotes to assign value, even though you explicitly declared them as number. This should work:

<ui-voter voteCount=20 myVote=0></ui-voter>

+ operator can be used to concat two strings, but -, * and / can't operate with strings and I guess that's what created confusion. When you assign value to number type variables, you should always do it without quotes.

Upvotes: 1

Related Questions