Angular2:+运算符将数字类型转换为字符串

时间:2016-09-19 20:05:11

标签: angular binding operators

任何人都可以解释为什么我的绑定中的'+'运算符将我的变量连接成字符串,而其他算术运算符如 - ,*和/正确地对它们进行算术运算作为数字,这是它们在相关的打字稿文件。

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>

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--;
    }
}

app.component.html文件中使用此组件的行

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

1 个答案:

答案 0 :(得分:1)

删除引号,voteCountmyVote在使用双引号分配值时被解释为string,即使您明确声明它们为number。这应该有效:

<ui-voter voteCount=20 myVote=0></ui-voter>
可以使用

+运算符来连接两个字符串,但-*/无法使用字符串进行操作,我想这就是&#39;什么造成了混乱。为number类型变量赋值时,应始终不带引号。

相关问题