如何用Angular的*ngFor将多维数组渲染为指定结构的表格?
Angular *ngFor 表格渲染问题解决
问题描述
我有三个数组:
dates: ['2022-01-01', '2022-02-01'] uniqueNames: ['a', 'b'] finalTableData: [ [ {name: 'a', amount: 200}, {name: 'a', amount: 100} ], [ {name: 'b', amount: 200}, {name: 'b', amount: 100} ] ]
希望用*ngFor渲染出如下结构的表格:
<table> <tr> <th></th> <th scope="col">2022-01-01</th> <th scope="col">2022-02-01</th> </tr> <tr> <th scope="row">a</th> <td>200</td> <td>100</td> </tr> <tr> <th scope="row">b</th> <td>200</td> <td>100</td> </tr> </table>
当前实现代码:
<table> <thead> <tr> <th class="w-25"></th> <ng-container *ngFor="let dat of dates;"> <th class="">{{dat}}</th> </ng-container> </tr> </thead> <tr> <tr *ngFor="let row of uniqueNames;"> <th>{{row}}</th> <table> <tr *ngFor="let data of finalTableData; let i = index"> <td *ngFor="let item of data">{{item.amount}} </td> </tr> </table> </tr> </table>
问题:无法将finalTableData的数据对应到每一行,而是把整个多维数组内容都加到了每一行里。
解决方案
问题出在嵌套了多余的<table>标签,并且遍历了整个finalTableData数组,没有根据当前行的索引匹配对应数据。正确做法是遍历uniqueNames时获取索引,用索引从finalTableData中取出对应行的金额数据,直接遍历渲染即可。
修正后的代码:
<table> <thead> <tr> <th class="w-25"></th> <ng-container *ngFor="let dat of dates;"> <th>{{dat}}</th> </ng-container> </tr> </thead> <tbody> <!-- 遍历名称时获取当前行索引 --> <tr *ngFor="let name of uniqueNames; let i = index"> <th scope="row">{{name}}</th> <!-- 通过索引匹配对应金额数组,遍历渲染每个金额 --> <td *ngFor="let item of finalTableData[i]">{{item.amount}}</td> </tr> </tbody> </table>
关键修改点:
- 移除嵌套的
<table>标签,保证表格结构合法 - 遍历
uniqueNames时添加let i = index,拿到当前行的索引值 - 用
finalTableData[i]获取当前名称对应的金额数组,再遍历取出每个amount
这样就能实现预期的表格结构,每个名称行对应自己的金额数据。
内容的提问来源于stack exchange,提问作者Eduardo Har
相关产品推荐
相关产品推荐

