求助:Angular 13中仅用HTML Table实现嵌套表格的方法
Angular 13 原生HTML Table实现主题与子主题嵌套方案
核心思路
通过Angular内置指令(*ngIf、*ngFor)结合HTML Table的colspan属性,实现主主题行点击展开/收起子主题行的效果,全程不依赖第三方库。
1. 定义数据结构
在组件类中定义符合主题-子主题层级的数据模型,给每个主主题添加expanded属性控制展开状态:
// component.ts import { Component } from '@angular/core'; interface SubTopic { name: string; description: string; status: string; } interface Topic { id: number; name: string; category: string; expanded: boolean; subTopics: SubTopic[]; } @Component({ selector: 'app-nested-table', templateUrl: './nested-table.component.html', styleUrls: ['./nested-table.component.css'] }) export class NestedTableComponent { topics: Topic[] = [ { id: 1, name: "主主题1", category: "分类A", expanded: false, subTopics: [ { name: "子主题1-1", description: "子主题描述内容1", status: "已完成" }, { name: "子主题1-2", description: "子主题描述内容2", status: "进行中" } ] }, { id: 2, name: "主主题2", category: "分类B", expanded: false, subTopics: [ { name: "子主题2-1", description: "子主题描述内容3", status: "未开始" } ] } ]; toggleExpand(topic: Topic): void { topic.expanded = !topic.expanded; } }
2. 编写HTML模板
利用*ngFor循环渲染主主题行,通过*ngIf控制子主题行的显示,子主题行使用colspan占满所有列:
<!-- component.html --> <table class="nested-table"> <thead> <tr> <th>主题名称</th> <th>分类</th> <th>状态</th> <th>操作</th> </tr> </thead> <tbody> <!-- 主主题行 --> <tr *ngFor="let topic of topics" class="main-row" (click)="toggleExpand(topic)"> <td>{{ topic.name }}</td> <td>{{ topic.category }}</td> <td>-</td> <td>{{ topic.expanded ? '收起' : '展开' }}</td> </tr> <!-- 子主题行 --> <tr *ngFor="let topic of topics" *ngIf="topic.expanded" class="sub-row"> <td colspan="4"> <table class="sub-table"> <tr *ngFor="let sub of topic.subTopics"> <td>{{ sub.name }}</td> <td>{{ sub.description }}</td> <td>{{ sub.status }}</td> <td>-</td> </tr> </table> </td> </tr> </tbody> </table>
3. 添加基础样式
通过CSS区分主/子行样式,优化视觉层级:
/* component.css */ .nested-table { width: 100%; border-collapse: collapse; border: 1px solid #ddd; } .nested-table th, .nested-table td { border: 1px solid #ddd; padding: 8px; text-align: left; } .nested-table th { background-color: #f2f2f2; } .main-row { cursor: pointer; background-color: #f9f9f9; } .main-row:hover { background-color: #f1f1f1; } .sub-row { background-color: #fff; } .sub-table { width: 100%; border-collapse: collapse; } .sub-table td { border: none; padding-left: 24px; /* 子主题缩进,增强层级感 */ }
关键细节说明
expanded属性:每个主主题对象自带的布尔属性,用于控制子主题行的显示/隐藏colspan="4":让子主题行的单元格占满主表格的所有列,避免布局错乱- 嵌套子表格:在子行的单元格内嵌套小型表格,实现子主题的结构化展示
- 点击交互:主行绑定
click事件调用toggleExpand方法,切换展开状态
内容的提问来源于stack exchange,提问作者Wasim Baba
相关产品推荐
相关产品推荐

