首页 > 解决方案 > 行数据与列的动态绑定

问题描述

我在 Angular 5 中动态绑定表数据的方法。

TS:

    columnList = [{
           name: "info.xyz",
           title: "Xyz"
            }];

HTML:

 <table>
    <thead>
        <tr>
            <th *ngFor="let c of columnsList">
                        {{c.title}}     
            </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let data of dataList">
            <td *ngFor="let c of columnsList">
                <div>
                    <div>
                        {{data[c.name]}}
                    </div>
                </div>
            </td>
        </tr>
    </tbody>
</table>

dataList 变量是我从 API 有效负载中获得的。它看起来像 API:

{
info:{
    xyz:4
    }
}

我正在尝试根据列中的标题动态显示行数据。但是,html 不会接受 {{data[c.name]}} 因为 c.name 本身就是 info.xyz 但是如果 c.name 是没有点的单个层次结构,它可以正常工作,因为它需要数据 [信息]。但是,API 数据必须没有负载。即 data[info.xyz] 不起作用(如帖子中所示)

有解决方法吗?

标签: htmlangularbindingangular5

解决方案


像这样试试

columnsList = [
{
  level1: "test",
  level2: "xyz",
  level3: "pqr",
  title: "Pqr"
},
{
  level1: "info",
  level2: "xyz",
  title: "Xyz"
},
{
  level1: "abc",
  title: "Abc"
}

];

dataList = [{
info: {
  xyz: 4
},
abc : 5,
test: {
  xyz : {
    pqr : 17
  }
}

}];

<table class="kruti">
<thead>
    <tr>
        <th *ngFor="let c of columnsList">
             {{c.title}}     
        </th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let data of dataList">
        <td *ngFor="let c of columnsList">
            <div>
                <div>
                  <span *ngIf="c.level3">{{data[c.level1][c.level2][c.level3]}}</span>
                  <span *ngIf="c.level2 && !c.level3">{{data[c.level1][c.level2]}}</span>
                  <span *ngIf="!c.level2 && !c.level3">{{data[c.level1]}}</span>
                </div>
            </div>
        </td>
    </tr>
</tbody>


推荐阅读