Display array of objects in table


I’m trying to display a list of objects in a table. But its only displaying the first row

This is the code I’m using

<table >
      <tr *ngFor="let part of allParts;">
        <td ><span>{{part.partId}}</span></td>
        <td ><span>{{part.partDesc}}</span></td>
        <td ><span>{{part.createdBy.firstName}}</span></td>
        <td ><span>{{part.updatedBy.firstName}}</span></td>
        <td ><span>{{part.createdDate | slice:0:10}}</span></td>
        <td ><span>{{part.updatedDate| slice:0:10}}</span></td>

only first object visible in table

When I use it in li tag as below it shows all the rows

    <li *ngFor="let part of allParts">{{part |json}}</li>

all objects visible in ul


{ "partId": 1, "partName": "", "partDesc": "", "createdBy": { "firstName": "John", "lastName": "Doe", "email": "john.doe@gm.com", "password": "P@ssw0rd!", "companyName": "GM", "id": "abc123" }, "updatedBy": null, "partType": { "partTypeCode": "pt1", "partTypeDesc": "pt1desc" }, "createdDate": "2023-01-03T22:13:24.180+00:00", "updatedDate": null, "quantity": 1 }, { "partId": 2, "partName": "", "partDesc": "", "createdBy": { "firstName": "John", "lastName": "Doe", "email": "john.doe@gm.com", "password": "P@ssw0rd!", "companyName": "GM", "id": "abc123" }, "updatedBy": null, "partType": { "partTypeCode": "pt1", "partTypeDesc": "pt1desc" }, "createdDate": "2023-01-03T22:13:54.966+00:00", "updatedDate": null, "quantity": 1 },{ "partId": 3, "partName": "", "partDesc": "", "createdBy": { "firstName": "John", "lastName": "Doe", "email": "john.doe@gm.com", "password": "P@ssw0rd!", "companyName": "GM", "id": "abc123" }, "updatedBy": null, "partType": { "partTypeCode": "pt1", "partTypeDesc": "pt1desc" }, "createdDate": "2023-01-03T22:14:20.081+00:00", "updatedDate": null, "quantity": 1 }

What should I change in order to display all the objects of the array in the table

>Solution :

The problem was updatedBy was null and you can’t access firstName from null as below:


You need to apply ?. optional chaining to stop accessing nested property when detect it is null.


Or working with *ngIf

    <ng-container *ngIf="part.updatedBy">
      {{ part.updatedBy.firstName }}

Demo @ StackBlitz

Leave a Reply Cancel reply