Jesse W
Jesse W

Reputation: 91

Display key and array values using *ngFor in angular 9

JSON

{
 "cars":
{
  "12345": [1960, 1961, 1962],
  "4567": [2001, 2002]
}
}

HTML

<strong>Plate and year</strong>
<div *ngFor="let list of lists">
{{list.cars}}
</div>

I need to display like this:

Plate and year

12345- 1960, 1961, 1962.

4567- 2001, 2002.

Upvotes: 0

Views: 2476

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38807

Based on your data structure, you can achieve this using the KeyValuePipe and additional nested *ngFor. KeyValuePipe allows you to iterate over an object similar to Object.entries providing a key and value property for each item. In this case the value will be an array that you can iterate over using an *ngFor:

<strong>Plate and year</strong>
<div *ngFor="let list of lists">
  <div *ngFor="let car of list.cars | keyvalue">
    <div>{{car.key}} - <div *ngFor="let year of car.value">{{year}}</div>
    </div>
  </div>
</div>

Here is an example in action.

Hopefully that helps!

Upvotes: 3

Related Questions