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

Angular组件:API对象数据的Expansion Panel与表格实现问询

Angular 实现API数据折叠面板与表格展示

一、TS文件数据存储与处理

首先定义对应的数据类型,接收API返回的嵌套对象后,将其转换为便于模板遍历的数组结构:

// 定义子项的数据类型
interface SubItem {
  [key: string]: any;
}

// 定义API返回数据的整体类型
interface ApiResponse {
  [key: string]: SubItem;
}

@Component({
  selector: 'app-data-panel',
  templateUrl: './data-panel.component.html',
  styleUrls: ['./data-panel.component.css']
})
export class DataPanelComponent implements OnInit {
  // 存储处理后的数据,方便模板循环渲染
  panelData: Array<{ key: string; items: Array<{ subKey: string; value: any }> }> = [];

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // 调用API获取数据
    this.http.get<ApiResponse>('你的API接口地址').subscribe(response => {
      // 把原始嵌套对象转成可遍历的数组
      this.panelData = Object.entries(response).map(([key, subItems]) => ({
        key,
        items: Object.entries(subItems).map(([subKey, value]) => ({ subKey, value }))
      }));
    });
  }
}

二、HTML模板渲染实现

方案1:使用Angular Material折叠面板

如果项目中用了Angular Material,直接用mat-accordion和mat-expansion-panel实现折叠效果,展开后渲染无表头表格:

<mat-accordion>
  <mat-expansion-panel *ngFor="let panel of panelData">
    <mat-expansion-panel-header>
      <mat-panel-title>
        {{ panel.key }}
      </mat-panel-title>
    </mat-expansion-panel-header>

    <!-- 展开后显示的表格 -->
    <table>
      <tbody>
        <tr *ngFor="let item of panel.items">
          <td>{{ item.subKey }}</td>
          <td>|</td>
          <td>{{ item.value }}</td>
        </tr>
      </tbody>
    </table>
  </mat-expansion-panel>
</mat-accordion>

注意:使用Material组件需提前在模块中导入MatExpansionModule。

方案2:原生HTML折叠实现

如果不想依赖第三方组件,用原生<details>和<summary>标签也能实现相同效果:

<details *ngFor="let panel of panelData">
  <summary>{{ panel.key }}</summary>
  <table>
    <tbody>
      <tr *ngFor="let item of panel.items">
        <td>{{ item.subKey }}</td>
        <td>|</td>
        <td>{{ item.value }}</td>
      </tr>
    </tbody>
  </table>
</details>

可选样式优化

为了让表格排版更美观,可添加基础CSS:

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 12px;
}

td {
  padding: 8px 12px;
}

td:nth-child(2) {
  padding: 0 8px;
  font-weight: 600;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:05:19