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

Angular表格行展开/折叠实现:点击异行不关闭已展开嵌套表问题

问题根因

原来的实现仅用全局的openCoverages开关和indexSelectedCoverage单个变量记录唯一展开行,每次点击新行都会覆盖原有记录的索引,导致之前的展开行自动关闭,不符合多展开的需求。

修改方案

1. 调整组件逻辑

将单个展开状态存储改为集合存储,记录所有已展开的行索引:

// 替换原来的 openCoverages、indexSelectedCoverage 变量
expandedIndexes = new Set<number>();

selectItemCoverages(index: number) {
  if (this.expandedIndexes.has(index)) {
    // 点击已展开的当前行,执行折叠
    this.expandedIndexes.delete(index);
  } else {
    // 点击未展开的行,执行展开,不影响其他已展开行
    this.expandedIndexes.add(index);
  }
}

2. 调整HTML模板

修改子表格的显示判断条件,同时修正原代码里</tdr>的笔误为</tr>:

<table class="table">
  <thead>
    <tr class="header-row">
      <th class="header">Province</th>
    </tr>
  </thead>
  <tbody class="table-row-expanded" *ngFor="let covenant of covenants; let i = index">
    <tr class="table-row-not-expanded">
      <td class="cell" (click)="selectItemCoverages(i)"> {{ covenant.provinceID }}
        <ng-container *ngIf="expandedIndexes.has(i)">
          <table class="table">
            <thead>
              <tr class="header-row">
                <th class="header">header 1</th>
                <th class="header">header 2</th>
                <th class="header">header 3</th>
              </tr>
            </thead>
            <tbody>
              <tr class="table-row">
                <td class="cell">1</td>
                <td class="cell">2</td>
                <td class="cell">3</td>
              </tr>
            </tbody>
          </table>
        </ng-container>
      </td>
    </tr>
  </tbody>
</table>

修改后即可实现需求:仅点击当前行时切换自身的展开/折叠状态,点击其他行不会关闭已展开的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:27:04