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

如何基于API数据在Angular中创建带动态列的计数表格

Angular 动态工位计数表格实现方案

根据需求,我们需要将API返回的产品数据转化为产品为行、工位为列的计数表格,每个单元格展示对应产品在该工位的统计数。以下是具体实现步骤:

1. 定义数据接口

先在组件中定义对应的数据类型,做类型校验:

interface StationCount {
  [key: string]: number;
}

interface Product {
  productId: number;
  productName: string;
  stationCount: StationCount;
}

2. 组件逻辑处理

在组件类中,从API数据里提取所有工位名称作为表格列头,同时保存产品列表:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-station-table',
  templateUrl: './station-table.component.html',
  styleUrls: ['./station-table.component.css']
})
export class StationTableComponent implements OnInit {
  products: Product[] = [];
  stations: string[] = [];

  ngOnInit(): void {
    // 这里替换为你的实际API请求
    const apiData = [
      {
        "productId": 1,
        "productName": "250 litre",
        "stationCount": {
          "Assembly": 1,
          "Moulding": 0,
          "Polishing": 1,
          "Post Mould Graphic Install": 0,
          "Product Wrapping": 0,
          "Spin Welding": 0,
          "Spin Welding Drainage Outlet": 0,
          "Trimming": 0,
          "Wheel Assembly": 3
        }
      },
      {
        "productId": 2,
        "productName": "300 litre",
        "stationCount": {
          "Assembly": 0,
          "Moulding": 3,
          "Polishing": 0,
          "Post Mould Graphic Install": 1,
          "Product Wrapping": 0,
          "Spin Welding": 0,
          "Spin Welding Drainage Outlet": 1,
          "Trimming": 1,
          "Wheel Assembly": 0
        }
      } 
    ];

    this.products = apiData;
    // 从第一个产品中提取工位名称作为列头
    if (this.products.length > 0) {
      this.stations = Object.keys(this.products[0].stationCount);
    }
  }
}

3. HTML模板实现

通过*ngFor动态渲染表头和表格行,每个单元格根据工位名称匹配对应产品的计数:

<table class="station-table">
  <thead>
    <tr>
      <th>产品名称</th>
      <!-- 动态生成工位列头 -->
      <th *ngFor="let station of stations">{{ station }}</th>
    </tr>
  </thead>
  <tbody>
    <!-- 遍历产品生成数据行 -->
    <tr *ngFor="let product of products">
      <td>{{ product.productName }}</td>
      <!-- 匹配对应工位的计数 -->
      <td *ngFor="let station of stations">{{ product.stationCount[station] }}</td>
    </tr>
  </tbody>
</table>

4. 样式调整(匹配参考效果)

添加CSS样式让表格更美观:

.station-table {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
  font-size: 14px;
  text-align: center;
}

.station-table th, .station-table td {
  border: 1px solid #ddd;
  padding: 12px;
}

.station-table thead tr {
  background-color: #f5f5f5;
  font-weight: bold;
}

.station-table tbody tr:nth-of-type(even) {
  background-color: #f9f9f9;
}

.station-table tbody tr:hover {
  background-color: #f1f1f1;
}

补充说明

如果不同产品的工位列表可能不一致,需要先合并所有产品的工位名称,避免列缺失;实际项目中,把模拟的apiData替换为Angular HttpClient的请求结果即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 16:46:14