通过“双向”绑定(bind)从我的 HTML 文件到我的 TS 文件的数据。
单个元素显示正确输出,但表达式显示输出 NaN。
我的 HTML 代码。
<div id="que1">
<p>What is your estimated savings?</p>
<form novalidate [formGroup]="quesForm">
<input ref-filter type="number" formControlName="estimatedsavings" [(ngModel)]="estimatedSavings">
<button type="submit" (click)="onSubmitQ1()" [disabled]="!filter.value">Submit</button>
</form>
</div>
<div id="que2">
<p>What is your combined family income?</p>
<form novalidate [formGroup]="quesForm">
<input ref-filtert type="number" formControlName="familyincome" [(ngModel)]="familyIncome">
<button type="submit" (click)="onSubmitQ4()" [disabled]="!filtert.value">Submit</button>
</form>
</div>
我的TS文件
quesForm: FormGroup;
estimatedSavings:number;
familyIncome:number;
totalSavings:number = (this.estimatedSavings - this.familyIncome);
onSubmitQ4 = function() {
console.log(this.childrengoingtoCollege);
console.log(this.totalSavings);
console.log(typeof(this.totalSavings));
}
最佳答案
totalSavings
由组件的初始化在您的代码中计算一次。这一刻 estimatedSavings
和 familyIncome
是 undefined
。您可以设置默认值并以这种方式使用 getter:
.ts 文件:
familyIncome:number = 0;
totalSavings:number = 0;
get totalSavings():number {
return this.estimatedSavings - this.familyIncome;
}
关于javascript - 显示 NaN 输出的 Js 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55489027/