arcticlisa
arcticlisa

Reputation: 73

Ensure array isn't empty when looping with ngFor

I need to display data from an array in a table. What condition can I use to ensure that the array should not be iterated when it is empty?

<tr *ngFor="let something of (adunit.unit_price)">
<td>{{something.updated_date | date : 'medium' }}</td>
<td>{{ something.value }}</td>

Upvotes: 1

Views: 3369

Answers (3)

Anthony DiTomasso
Anthony DiTomasso

Reputation: 556

I would add an Elvis operator which will check for the existence of the parent variable first. Like this:

<tr *ngFor="let something of adunit?.unit_price">
<td>{{something.updated_date | date : 'medium' }}</td>
<td>{{ something.value }}</td>

Upvotes: 1

r2018
r2018

Reputation: 545

You don't need to worry about iteration, as Angular will take care of it for you. If array is empty, it won't iterate.

Upvotes: 1

bugs
bugs

Reputation: 15323

You can wrap your table inside an *ngIf

<table *ngIf="adunit.unit_price.length">
  <tr *ngFor="let something of (adunit.unit_price)">
  <td>{{something.updated_date | date : 'medium' }}</td>
  <td>{{ something.value }}</td>
  </tr>
</table>

Upvotes: 5

Related Questions