Angular ngFor iterating over more than one HTML item

Viewed 51

I have a very simple Object (which I build from a JSON) and I want to display it as a description list. I would like to have the view of my Angular component like this:

<dl>
   <dt> key1 </dt>
   <dd> value1 </dd>
   <dt> key2 </dt>
   <dd> value2 </dd>
   ...
</dl>

How can I have the ngFor directive repeating more than one HTML item?

Thanks

1 Answers

Use the KeyValuePipe:

<dl>
  <ng-container *ngFor="let item of yourObject | keyvalue">
    <dt>{{item.key}}</dt>
    <dd>{{item.value}}</dd>
  </ng-container>
</dl>

Maybe it is also worth to check if yourObject exists with some use of NgIf:

<dl *ngIf="yourObject; else noObject">
  <ng-container *ngFor="let item of yourObject | keyvalue">
    <dt>{{item.key}}</dt>
    <dd>{{item.value}}</dd>
  </ng-container>
</dl>
<ng-template #noObject>
  No object.
</ng-template>
Related