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

Angular中如何将数据插入HTML属性?可折叠表格语法求助

Angular *ngFor生成可折叠表格的正确写法

你当前代码的问题在于使用了错误的Angular插值语法[[user.id]],同时折叠行不在*ngFor作用域内,导致user变量无法访问。以下是修正方案:

核心修改点

  • 替换错误的[[user.id]]为Angular标准的插值表达式{{user.id}},或使用属性绑定语法
  • 将折叠行放入*ngFor的作用域中,确保每个用户的主行和折叠行一一对应

修正后的完整代码示例

<table class="table table-condensed table-striped">
  <thead>
    <tr>
      <th></th>
      <th>First Name</th>
      <th>Last Name</th>
    </tr>
  </thead>

  <tbody>
    <!-- 使用ng-container包裹循环内的两行,避免额外DOM元素 -->
    <ng-container *ngFor="let user of viewUsers">
      <!-- 主行:触发折叠的行 -->
      <tr
        data-toggle="collapse"
        data-target="#demo{{user.id}}"
        class="accordion-toggle"
      >
        <td>
          <button class="btn btn-default btn-xs">
            <span class="glyphicon glyphicon-eye-open"></span>
          </button>
        </td>
        <td>{{ user.firstName }}</td>
        <td>{{ user.lastName }}</td>
      </tr>

      <!-- 折叠行:对应主行的详情区域 -->
      <tr>
        <td colspan="12" class="hiddenRow">
          <div class="accordian-body collapse" id="demo{{user.id}}">
            <table class="table table-striped">
              <thead>
                <tr class="info">
                  <th>Job</th>
                  <th>Company</th>
                  <th>Salary</th>
                  <th>Date On</th>
                  <th>Date off</th>
                  <th>Action</th>
                </tr>
              </thead>
              <!-- 这里可以继续填充用户的详情数据 -->
            </table>
          </div>
        </td>
      </tr>
    </ng-container>
  </tbody>
</table>

两种属性绑定方式说明

方式1:插值表达式(直观简洁)

直接在属性值中拼接字符串:

data-target="#demo{{user.id}}"
id="demo{{user.id}}"

方式2:Angular属性绑定(更规范)

使用[attr.属性名]的绑定语法,适合复杂的字符串拼接逻辑:

[attr.data-target]="'#demo' + user.id"
[attr.id]="'demo' + user.id"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:36:09