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

如何解决Angular表格表头重复显示的问题

解决Angular中*ngFor遍历导致表格表头重复的问题

问题分析

你当前的代码把整个<table>标签放在了*ngFor循环内部,导致每一条符合queryName === "style-size-query"的记录都会生成一个完整的表格,自然表头会重复显示。要让所有符合条件的记录共享同一个表头,需要把表格结构拆分:表头放在循环外,只在表格的<tbody>里遍历数据。

方案1:模板内直接过滤(适合简单场景)

修改代码,将<table>和<thead>移到循环外面,在<tbody>中使用*ngFor结合条件过滤,同时修正原表头的排版问题(原写法会让每个表头单独占一行):

<table class="table">
  <thead>
    <tr>
      <th>product</th>
      <th>size</th>
      <th>sortOrder</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let recordData of employees.record" 
        *ngIf="recordData.queryName === 'style-size-query'">
      <td>{{recordData.data.product}}</td>
      <td>{{recordData.data.size}}</td>
      <td>{{recordData.data.sortOrder}}</td>
    </tr>
  </tbody>
</table>

方案2:组件内提前过滤数据(推荐,性能更优)

在组件的.ts文件中先过滤出符合条件的记录,模板直接遍历过滤后的数组,避免在模板中频繁执行条件判断,同时让模板结构更简洁:

组件代码(.ts)

// 假设组件类中已有employees数据
filteredRecords: any[] = [];

ngOnInit() {
  // 初始化时过滤数据
  this.filteredRecords = this.employees.record.filter(record => 
    record.queryName === 'style-size-query'
  );
}

// 若employees是异步加载(比如接口请求),需在数据返回后执行过滤
// 示例:
// this.apiService.getEmployees().subscribe(data => {
//   this.employees = data;
//   this.filteredRecords = this.employees.record.filter(record => 
//     record.queryName === 'style-size-query'
//   );
// });

模板代码(.html)

<table class="table">
  <thead>
    <tr>
      <th>product</th>
      <th>size</th>
      <th>sortOrder</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let recordData of filteredRecords">
      <td>{{recordData.data.product}}</td>
      <td>{{recordData.data.size}}</td>
      <td>{{recordData.data.sortOrder}}</td>
    </tr>
  </tbody>
</table>

修改后,所有符合条件的6条记录都会显示在同一个表头下方,不会再重复生成表格和表头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:33:13