1

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>

1 Answer 1

1

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.

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

1 Comment

That did the trick! Strange that it would overwrite my explicitly typed variables but there you have it! Thanks @Stefan.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.