1

I (think) I have a dictionary data set with the keys being a date and the value being at least one array

private dateArray = {};

I am dynamically loading more arrays to the dictionary array so that I can show them as different sections on the component. The goal is something like this:

Date Joined: 9/1/17

Name: Mary, Age: 40

Name: John, Age: 20

Date Joined: 10/1/17

Name: Jeff, Age: 30

dateArray ends up having the date as a string in the key and then the properties are added as multiple arrays of their specific properties.

{Fri Sept 1 2017: ([Name: Mary, Age: 40],[Name: John, Age: 20]),
Sun Oct 1 2017: [Name: Jeff, Age: 30]}

How do I access the data from the template side? I am using Angular 2. I tried the Mapping Object Keys section and did not have any luck getting anything to display. Is piping the best route in Angular 2?

cooper
  • 417
  • 1
  • 10
  • 20
  • 1
    I would argue that 'private dateArray = {};' is not a good name for this variable/object. When you declare this variable with {}, you are not creatring an array. You better use another name, so it would have a better meaning. – Christian Benseler Oct 16 '17 at 18:08

2 Answers2

2

Maybe you can create a property with the keys, iterate over them and then get the array for each key (as long as you can only use ngFor with an iterable, and an json-like/hash object, as this {}, is not iterable).

.ts

this.keys = Object.keys(dateDictionary)

.html

<div *ngFor="let key of keys">
  <div *ngFor="let date of dateDictionary[key]">
    <p>{{ date.date }}</p>
    <p>{{ date.Name }}</p>
    <p>{{ date.Age }}</p>
  </div>  
</div>
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71
0

First you need to declare dateArray as public. The template access only the public members.

After that you can do in the template something like this:

<div *ngFor="let date of dateArray">
  <p>{{ date.date }}</p>
  <p>{{ date.Name }}</p>
  <p>{{ date.Age }}</p>
</div>

Hint: the dateArray array should be like this:

[
  {
    "date": "Fri Sept 1 2017",
    "Name": "test1",
    "Age": "12"
  },
  {
    "date": "Fri Sept 1 2017",
    "Name": "test2",
    "Age": "2"
  }
]
Peter Kota
  • 8,048
  • 5
  • 25
  • 51