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

Angular 4中如何通过*ngFor变量拼接访问profile对象属性?

解决Angular 4中动态访问对象属性与嵌套*ngFor的问题

首先得指出你代码里的两个关键问题:

  1. Angular不允许在同一个元素上绑定多个*ngFor指令,得用<ng-container>来拆分循环——它不会生成额外DOM节点,很适合这种场景。
  2. 你尝试用{{ profile.{{columnName}} }}的方式访问动态属性是错误语法,Angular插值表达式里不能嵌套插值,要访问变量对应的对象属性,得用方括号属性访问语法:profile[columnName]。

接下来给你两种常见场景的正确实现:

场景1:生成标准列展示表格(每行对应一个profile的所有列数据)

如果你的需求是做一个常规表格,表头是defaultColumns的列名,每一行对应一个profile的各列属性值,代码应该这样写:

<table>
  <!-- 表头 -->
  <tr>
    <th *ngFor="let columnName of defaultColumns">
      {{ columnName }}
    </th>
  </tr>
  <!-- 表体数据行 -->
  <tr *ngFor="let profile of allSupprotProfiles">
    <td *ngFor="let columnName of defaultColumns">
      {{ profile[columnName] }}
    </td>
  </tr>
</table>

场景2:每行展示单个列名与对应所有profile的属性值

如果你的需求是每行显示一个列名,然后依次展示每个profile的该列属性(比如纵向排版的表格),就需要用<ng-container>来嵌套循环:

<table>
  <ng-container *ngFor="let columnName of defaultColumns">
    <tr>
      <th>{{ columnName }}</th>
      <td *ngFor="let profile of allSupprotProfiles">
        {{ profile[columnName] }}
      </td>
    </tr>
  </ng-container>
</table>

核心要点再强调下:

  • 动态属性访问必须用obj[variableName]的形式,.语法只能用于固定属性名,无法识别变量。
  • 多个*ngFor要拆分到不同元素上,<ng-container>是最佳选择,不会污染DOM结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:15:46