Angular HTML模板中遍历嵌套JSON动态生成嵌套行列结构的实现方案
实现方案
步骤1:组件类中定义数据结构
首先在组件TS文件中定义对应的数据类型,同时绑定你的JSON数据:
import { Component } from '@angular/core'; // 定义列元素结构 interface ColElement { id: string; rowElements: RowElement[]; } // 定义行元素结构 interface RowElement { id: string; colElements: ColElement[]; } @Component({ selector: 'app-nested-layout', templateUrl: './nested-layout.component.html', styleUrls: ['./nested-layout.component.css'] }) export class NestedLayoutComponent { // 绑定你的JSON数据 container = { "id": "37ec0632-3391-4ef5-a9cb-25db2216fa75", "rowElements": [ { "id": "80e1dae7-b497-48d3-80ad-b94d36ada642", "colElements": [ { "id": "c662efe9-615c-4de5-97d3-2b02a5bce831", "rowElements": [ { "id": "b31960fd-c082-4d3b-88fc-c05f0cf837aa", "colElements": [] }, { "id": "7552306a-ca61-4d80-bb4e-d6c8d15c2c78", "colElements": [] }, { "id": "f669896d-132b-468e-8dcf-f2b59d509a76", "colElements": [] } ] } ] } ] } }
步骤2:模板中实现递归渲染
由于你的结构是行、列互相嵌套的递归结构,用ng-template配合ngTemplateOutlet实现递归渲染是最优方案,无需额外创建子组件,支持任意层级的嵌套:
<!-- 入口:渲染最外层容器下的所有行 --> <ng-container *ngFor="let row of container.rowElements"> <ng-template [ngTemplateOutlet]="rowTemplate" [ngTemplateOutletContext]="{ $implicit: row }" ></ng-template> </ng-container> <!-- 行模板:渲染row类div,内部遍历所有列 --> <ng-template #rowTemplate let-row> <div class="row" [attr.data-id]="row.id"> <ng-container *ngFor="let col of row.colElements"> <ng-template [ngTemplateOutlet]="colTemplate" [ngTemplateOutletContext]="{ $implicit: col }" ></ng-template> </ng-container> </div> </ng-template> <!-- 列模板:渲染col类div,内部遍历所有嵌套的行 --> <ng-template #colTemplate let-col> <div class="col" [attr.data-id]="col.id"> <ng-container *ngFor="let nestedRow of col.rowElements"> <ng-template [ngTemplateOutlet]="rowTemplate" [ngTemplateOutletContext]="{ $implicit: nestedRow }" ></ng-template> </ng-container> </div> </ng-template>
实现说明
- 两个模板互相调用,无需手动写固定层级的循环,自动适配任意深度的嵌套结构
- 当
rowElements或colElements为空数组时,*ngFor自动停止渲染,不会出现死循环问题 - 代码中
[attr.data-id]是为了方便调试绑定原始数据ID,不需要可以直接删除 - 如果需要在行/列中插入自定义内容,直接在对应模板的div内部添加代码即可
如果你需要在行/列中封装更复杂的交互逻辑,也可以拆分为两个独立组件
<app-row>和<app-col>,在组件模板中互相引用实现递归,原理和模板递归完全一致。
内容的提问来源于stack exchange,提问作者PureFlow
相关产品推荐
相关产品推荐

