在Angular表中显示json数据

时间:2019-09-02 07:55:52

标签: json angular typescript

我有这样的json结果

{
    "discipline":"ACLS",
    "course": [
                    {
            "value":"ACLS Initial",
            "classes":"0",
            "students":"0"
        },
        {
            "BLS":"CPR Instructor Class",
            "classes":"0",
            "students":"0"
        }       
       ]    
} 

并且我需要在image这样的表格中显示此列表 我知道如何在Angular的表中显示数据,但是这个特定的json集及其所需的设计使我感到困惑。在其他表格中,我显示了这样的数据

<table class="table table-hover table-striped">
          <thead>
              <tr>
                      <th>Date/Time</th>
                      <th>Course</th>
                      <th>Location</th>
                      <th>Instructor</th>
                      <th>Enrolled</th>
                      <th>Actions</th>
              </tr>
          </thead>
          <tbody>
              <tr>
                  <td class="trim">25/6/2019</td>
                  <td class="trim">Chemistry</td>
                  <td class="trim">Islamabad</td>
                  <td class="trim">Shaharyar</td>
                  <td class="trim">Yes</td>     
                  <td class="trim">
                    <nb-select>

                      <nb-option value="2">Edit</nb-option>
                      <nb-option value="3">Delete</nb-option>
                      <nb-option value="4">View</nb-option>
                    </nb-select>
                  </td>
              </tr>
          </tbody>
      </table>

您能告诉我如何在表格中显示上述json吗? 附注:我只是假设json会是这样,但我尚未为API编写代码。

1 个答案:

答案 0 :(得分:2)

您需要对数据使用与在OP中发布的数据不同的结构。

您可以改为为disciplines创建一个对象数组,其中每个对象将代表一个discipline。在每个discipline中,可以有多个courses,因此添加一个courses键,其值将是对象数组,其中每个对象将代表一个course

disciplines的新数据结构看起来像这样

[{
    "name": "ACLS",
    "courses": [{
        "name": "ACLS Initial",
        "classes": "0",
        "students": "0"
    }, {
        "name": "ACLS Renewal course",
        "classes": "0",
        "students": "0"
    }]
}, {
    "name": "BLS",
    "courses": [{
        "name": "CPR Instructor Class",
        "classes": "0",
        "students": "0"
    }]
}]

现在,您只需要使用嵌套的ngFor在UI中显示数据。

<tbody>
    <ng-container *ngFor="let discipline of disciplines">
        <tr>
            <td>{{discipline.name}}</td>
        </tr>
        <tr *ngFor="let course of discipline.courses">
            <td></td>
            <td>{{course.name}}</td>
            <td>{{course.classes}}</td>
            <td>{{course.students}}</td>
        </tr>
    </ng-container>
</tbody>

这是StackBlitz上的一个有效示例。