【问题标题】:Angular2: + operator converting number types to stringsAngular2:+运算符将数字类型转换为字符串
【发布时间】:2016-09-19 20:05:10
【问题描述】:

谁能解释为什么我的绑定中的“+”运算符将我的变量连接为字符串,而其他算术运算符(例如 -、* 和 /)正确地将它们作为数字进行算术运算,这是它们在关联的打字稿文件。

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>

【问题讨论】:

    标签: angular binding operators


    【解决方案1】:

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

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

    + 运算符可用于连接两个字符串,但 -*/ 不能对字符串进行操作,我猜这就是造成混乱的原因。当你给number 类型变量赋值时,你应该总是不带引号。

    【讨论】:

    • 成功了!奇怪的是它会覆盖我显式类型的变量,但你有它!谢谢@Stefan。
    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    相关资源
    最近更新 更多