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

Angular中*ngFor加载动态表头异常:表头堆叠至单列

解决Angular动态表头堆叠问题

嘿,我一眼就找到问题根源啦!

你当前的代码里,把*ngFor指令放在了<tr>标签上——这就意味着每个表头字段都会生成一个独立的表格行,所有<th>自然会挤在同一列里堆叠起来,完全不符合横向排列的预期。

修正后的HTML代码

只需要把循环从<tr>移到<th>上,让所有表头单元格都处于同一个表格行内:

<thead>
  <tr>
    <!-- 把*ngFor放在<th>标签上,所有表头横向排列 -->
    <th class='table-header' *ngFor="let title of headers">
      {{title['COLUMN_NAME']}}
    </th>
  </tr>
</thead>
<tbody>
  <tr *ngFor="let item of data | paginate : {itemsPerPage: 25, currentPage: p} ">
    <td>{{item.ID}}</td>
    <td>{{item['78d00422ce41_POWER']}}</td>
    <td>{{item['78d00422ce41_TIME']}}</td>
    <td>{{item['78d00422821c_POWER']}}</td>
    <td>{{item['78d00422821c_TIME']}}</td>
  </tr>
</tbody>

额外优化建议

如果想让表格内容也跟着表头动态变化(不用硬编码字段名),可以同样循环headers数组来渲染<td>:

<tbody>
  <tr *ngFor="let item of data | paginate : {itemsPerPage: 25, currentPage: p} ">
    <td *ngFor="let title of headers">
      {{item[title.COLUMN_NAME]}}
    </td>
  </tr>
</tbody>

这样以后headers数组新增或修改字段时,表格内容会自动适配,不用手动修改<td>代码~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:53:51