简体   繁体   English

如何在HTML中的Typescript中迭代JSON数组?

[英]How to iterate a JSON array in typescript in HTML?

I have a snippets of JSON array as shown below: 我有一个JSON数组片段,如下所示:

[{
        "auction_number": "015",
        "email": "pete@abc.com",
        "first_name": "Peter",
        "last_name": "Dan",
        "table": 0,
        "id": "015"
    },
    {
        "auction_number": "024",
        "email": "dan@gog.com",
        "first_name": "Dan",
        "last_name": "Fain",
        "table": 0,
        "id": "024"
    }
]



Typescript Code: 打字稿代码:

The typescript (ts) for the above JSON array is shown below. 上面的JSON数组打字稿 (ts)如下所示。 Here attendees is an array object. 这里的attendees是一个数组对象。

attendees: Attendee[];
 constructor(public authService: AuthService) {
    const str = localStorage.getItem("attendees");
    if(str) {
      this.attendees = JSON.parse(str);
      console.log(str);
    }
  }


HTML Code: HTML代码:

The HTML code which I have used in order to iterate everything from the JSON array (in the typescript code) is shown below. 下面显示了我用来迭代JSON数组中所有内容的HTML代码 (在打字稿代码中) For some reasons, it is not able to iterate attendees in the HTML. 由于某些原因,它无法迭代HTML中的attendees

<tr *ngFor="let row of attendees">
   <td class="left">{{ attendees.first_name }} {{ attendees.last_name }}</td>
   <td class="number1">250</td>
   <td class="table1">{{attendees.table}}</td>
   <td class="right-bill">Bill</td>
</tr>



Problem Statement: 问题陈述:

I am wondering what changes I should make in the HTML code above so that I am successfully able to iterate attendees array. 我想知道我应该在上面HTML代码中进行哪些更改以便我能够成功地迭代attendees数组。 I tried using ngfor directive but somehow it didn't work. 我尝试使用ngfor指令,但是以某种方式无法正常工作。

You should reference fields in each row as row.first_name because you set each attendee as let row of attendees . 您应该将每一行中的字段都引用为row.first_name因为您将每个与会者都设置为let row of attendees The variable you defined is row . 您定义的变量是row

You are accessing the parent loop again, you should access only the elements of row 您正在再次访问父循环,您应该只访问row的元素

<tr *ngFor="let row of attendees">
   <td class="left">{{ row .first_name }} {{ row .last_name }}</td>
   <td class="number1">250</td>
   <td class="table1">{{attendees.table}}</td>
   <td class="right-bill">Bill</td>
</tr>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM