Angular中如何在表格内渲染嵌套FormArray并实现rowspan合并
问题核心原因
你的写法存在3个错误导致子数组不显示、表格结构异常:
- 子数组循环加了
*ngIf="checkListindex > 0"的判断,直接过滤掉了第一条checklist数据 - 遍历checklist的源写错了:响应式表单中activity是FormGroup对象,子表单数组要通过
activity.get('check_lists')?.controls获取,不是直接取activity.check_lists - 所有checklist的
<td>都塞到了同一个<tr>里,不仅会导致单元格数量超出表头,也没法实现跨行合并效果
修正后代码
<table class="table table-xs table-sm table-hover"> <thead class="table-primary"> <tr> <th width="20%">Activity Name</th> <th width="15%">Activity Description</th> <th width="15%">Overall Percentage</th> <th width="10%">CheckList</th> <th width="10%">Weightage</th> </tr> </thead> <tbody> <ng-container formArrayName="activity_mappings" *ngFor="let activity of activityMappings['controls']; let i = index;"> <ng-container [formGroupName]="i"> <!-- 先获取当前活动的checklist总数,作为rowspan的值 --> <ng-container *ngIf="activity.get('check_lists')?.controls as checkLists"> <!-- 遍历所有checklist生成对应行 --> <tr *ngFor="let ch of checkLists; let checkListindex = index;" formArrayName="check_lists" [formGroupName]="checkListindex"> <!-- 只有第一行渲染三个合并列 --> <td *ngIf="checkListindex === 0" [attr.rowspan]="checkLists.length"> <input type="text" class="form-control form-control-sm" placeholder="Activity Name" formControlName="activity_name"/> </td> <td *ngIf="checkListindex === 0" [attr.rowspan]="checkLists.length"> <input type="text" class="form-control form-control-sm" placeholder="Description" formControlName="description"/> </td> <td *ngIf="checkListindex === 0" [attr.rowspan]="checkLists.length"> <input type="text" class="form-control form-control-sm" placeholder="Overall Percentage" formControlName="overall_percentage"/> </td> <!-- 每行都渲染checklist相关的两列 --> <td> <input type="text" class="form-control form-control-sm" placeholder="CheckList" formControlName="check_list_title"/> </td> <td> <input type="text" formControlName="weightage" class="form-control form-control-sm" placeholder="Weightage"/> </td> </tr> </ng-container> </ng-container> </ng-container> <tr *ngIf="activityMappings.length == 0"> <td class="text-center" colspan="5">No Activities Found</td> </tr> </tbody> </table>
实现逻辑说明
- 先取每个活动对应check_lists表单数组的长度,作为前三个列
rowspan的属性值,自动匹配需要合并的行数 - 遍历check_lists生成对应数量的行,仅在第一行渲染活动名称、描述、总占比三个列,其余行自动跳过这三个列,配合rowspan实现合并效果
- 所有行都正常渲染checklist标题和占比两列,保证每行单元格数量和表头一致
- 修复了空数据提示的
colspan值,从4改为5匹配表头列数
内容的提问来源于stack exchange,提问作者Sanjana
相关产品推荐
相关产品推荐

