首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何循环遍历对象数组,计算每年的年收入,并使用Angular 2将其显示在表中?

循环遍历对象数组,计算每年的年收入,并使用Angular 2将其显示在表中的步骤如下:

  1. 首先,创建一个对象数组,每个对象包含年份和收入字段。例如:
代码语言:txt
复制
const incomeData = [
  { year: 2019, income: 10000 },
  { year: 2020, income: 15000 },
  { year: 2021, income: 20000 }
];
  1. 在Angular 2中,可以使用*ngFor指令来循环遍历对象数组,并在表格中显示数据。在组件的HTML模板中,添加以下代码:
代码语言:txt
复制
<table>
  <thead>
    <tr>
      <th>年份</th>
      <th>年收入</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let data of incomeData">
      <td>{{ data.year }}</td>
      <td>{{ data.income }}</td>
    </tr>
  </tbody>
</table>
  1. 在组件的TypeScript代码中,定义incomeData数组,并计算每年的年收入。可以使用reduce方法来计算总收入。添加以下代码:
代码语言:txt
复制
import { Component } from '@angular/core';

@Component({
  selector: 'app-income-table',
  templateUrl: './income-table.component.html',
  styleUrls: ['./income-table.component.css']
})
export class IncomeTableComponent {
  incomeData = [
    { year: 2019, income: 10000 },
    { year: 2020, income: 15000 },
    { year: 2021, income: 20000 }
  ];

  calculateYearlyIncome(): number {
    return this.incomeData.reduce((total, data) => total + data.income, 0);
  }
}
  1. 最后,在组件的HTML模板中,显示总收入。添加以下代码:
代码语言:txt
复制
<p>总收入: {{ calculateYearlyIncome() }}</p>

这样,循环遍历对象数组,计算每年的年收入,并使用Angular 2将其显示在表中的功能就完成了。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券