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 >
<thead>
<tr>
<th>partId</th>
<th>partName</th>
<th>partDesc</th>
<th>partTypeCode</th>
<th>createdBy</th>
<th>updatedBy</th>
<th>createdDate</th>
<th>updatedDate</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let part of allParts;">
<td ><span>{{part.partId}}</span></td>
<td><span>{{part.partName}}</span></td>
<td ><span>{{part.partDesc}}</span></td>
<td><span>{{part.partTypeCode}}</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>
</tr>
</tbody>
</table>
only first object visible in table
When I use it in li tag as below it shows all the rows
<ul>
<li *ngFor="let part of allParts">{{part |json}}</li>
</ul>
allParts
{ "partId": 1, "partName": "", "partDesc": "", "createdBy": { "firstName": "John", "lastName": "Doe", "email": "[email protected]", "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": "[email protected]", "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": "[email protected]", "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
CodePudding user response:
The problem was updatedBy
was null
and you can't access firstName
from null
as below:
<td><span>{{part.updatedBy.firstName}}</span></td>
You need to apply ?.
optional chaining to stop accessing nested property when detect it is null.
<td><span>{{part.updatedBy?.firstName}}</span></td>
Or working with *ngIf
<td>
<span>
<ng-container *ngIf="part.updatedBy">
{{ part.updatedBy.firstName }}
</ng-container>
</span>
</td>