Angular:如何跨ngFor循环传递参数给函数以匹配表头对应值?
解决方案
问题核心在于你tbody里的*ngFor循环对象的键值对,这会导致单元格顺序和表头不匹配,正确的做法是循环表头数组headers,而非对象的键,这样就能直接拿到每个表头对应的header对象,再传递给setValue函数。
修改后的HTML代码:
<ng-container *ngIf="hfsTableSchema"> <table> <thead> <tr> <th *ngFor="let header of headers; let i = index">{{header.title}}</th> </tr> </thead> <tbody> <tr *ngFor="let object of rows"> <!-- 循环headers数组,而非object的键值对 --> <td *ngFor="let header of headers">{{setValue(object, header)}}</td> </tr> </tbody> </table> </ng-container>
对应的setValue函数保持你原本的逻辑即可:
setValue(object: any, header: any){ return object[header.title]; }
关键说明
- 循环
headers数组能保证单元格的顺序和表头完全一致,不受后端返回对象的键值对顺序影响 - 直接在td的
*ngFor中拿到当前表头的header对象,无需跨循环传递变量
内容的提问来源于stack exchange,提问作者3gwebtrain
相关产品推荐
相关产品推荐

