You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular租金计算器表格数据无法显示问题求助

解决Angular租金计算器表格渲染问题

问题根源

你当前的total数组仅存储了单个租金数值,但表格模板期望的是包含years、baseRent、New_rent字段的对象,因此row[column]无法找到对应属性,导致表格无法渲染数据。而注释的<h4>能正常显示,是因为它直接遍历数值,不需要对象属性匹配。

修改后的TypeScript代码

调整calculate方法,将每个年份的相关数据封装为对象存入total数组:

export class TableComponent implements OnInit {
  headers: string[] = ['years', 'baseRent', 'New_rent'];

  ngOnInit(): void {}

  constructor() {}

  increase: number = 0;
  years: number = 0;
  rent: number = 0;
  total: any[] = [];

  calculate() {
    this.total = [];
    let previousRent = this.rent;

    // 初始化第一年数据
    this.total.push({
      years: 1,
      baseRent: previousRent,
      New_rent: previousRent
    });

    // 从第2年开始计算租金涨幅
    for (let i = 2; i <= this.years; i++) {
      const currentRent = previousRent * (1 + this.increase / 100);
      const roundedRent = Math.round((currentRent + Number.EPSILON) * 100) / 100;

      this.total.push({
        years: i,
        baseRent: previousRent,
        New_rent: roundedRent
      });

      previousRent = roundedRent;
    }
  }
}

关键说明

  1. 每个数组元素改为包含years(年份)、baseRent(当年基础租金,即上一年租金)、New_rent(涨幅后的租金)的对象,完全匹配表格表头的字段。
  2. 修正循环逻辑,确保从第2年到指定年限的所有数据都能正确生成。
  3. 给变量添加类型声明,符合Angular代码规范。

额外注意事项

  • 确保你的模块(如AppModule)中已经导入FormsModule,否则[(ngModel)]双向绑定会失效:
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // 其他导入项
    FormsModule
  ]
})
export class AppModule {}
  • 可以给表格添加基础样式提升可读性:
#users {
  border-collapse: collapse;
  margin-top: 20px;
  width: 100%;
}
#users th, #users td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}
#users th {
  background-color: #f5f5f5;
  font-weight: bold;
}

内容的提问来源于stack exchange,提问作者Shahzeb Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:20:26