任何人都可以解释为什么我的绑定中的'+'运算符将我的变量连接成字符串,而其他算术运算符如 - ,*和/正确地对它们进行算术运算作为数字,这是它们在相关的打字稿文件。
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>
答案 0 :(得分:1)
删除引号,voteCount
和myVote
在使用双引号分配值时被解释为string
,即使您明确声明它们为number
。这应该有效:
<ui-voter voteCount=20 myVote=0></ui-voter>
可以使用 +
运算符来连接两个字符串,但-
,*
和/
无法使用字符串进行操作,我想这就是&#39;什么造成了混乱。为number
类型变量赋值时,应始终不带引号。