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

Angular:如何跨ngFor循环传递参数给函数以匹配表头对应值?

解决方案

问题核心在于你tbody里的*ngFor循环对象的键值对,这会导致单元格顺序和表头不匹配,正确的做法是循环表头数组headers,而非对象的键,这样就能直接拿到每个表头对应的header对象,再传递给setValue函数。

修改后的HTML代码:

<ng-container *ngIf="hfsTableSchema">
  <table>
    <thead>
      <tr>
        <th *ngFor="let header of headers; let i = index">{{header.title}}</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let object of rows">
        <!-- 循环headers数组,而非object的键值对 -->
        <td *ngFor="let header of headers">{{setValue(object, header)}}</td>
      </tr>
    </tbody>
  </table>
</ng-container>

对应的setValue函数保持你原本的逻辑即可:

setValue(object: any, header: any){
  return object[header.title];
}

关键说明

  • 循环headers数组能保证单元格的顺序和表头完全一致,不受后端返回对象的键值对顺序影响
  • 直接在td的*ngFor中拿到当前表头的header对象,无需跨循环传递变量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:20:24