0

I have an array of items and each item has a day number. There will be multiple items for each day but I want to dynamically construct a table with columns for each day. This is the code I have so far.

<table>
    <thead>
      <th *ngFor="let item of itemList|async">
        Day {{item.assignedPeriod.dayNumber}}
      </th>
    </thead>
  </table>

Obviously this produces a new column for each item regardless of whether a previous item has already been seen for that day. I want it to skip making a new column if the column already exists for the day and create one if it does not exist.

How do I go about that?

coolblue2000
  • 3,796
  • 10
  • 41
  • 62
  • You probably need to extract the unique day numbers from the `itemList` and iterate through those, rather than the items themselves – DaveMongoose Oct 10 '19 at 14:45
  • There must be a way to do an "IF" and only create a column if the day number does not match a currentDay component variable or something? – coolblue2000 Oct 10 '19 at 14:53
  • This seems like a very similar problem to https://stackoverflow.com/q/45373304/2208016 – DaveMongoose Oct 10 '19 at 15:28
  • I am not sure that is the same issue. I have no problem creating a list of days in code. I have an issue doing it in the template using directives etc. – coolblue2000 Oct 10 '19 at 19:19

1 Answers1

0

You need loop over your data and create an array of object. But I can imagine use the async pipe. Well you can use map over the observable to transform the data but I'm a bit lazy

Supouse you has as data some like:

data=[{day:1,name:"one",value:100},
  {day:1,name:"two",value:200},
  {day:2,name:"three",value:300},
  {day:1,name:"four",value:400},
  {day:3,name:"five",value:500},
  {day:2,name:"six",value:600}
  ]

You can make some like

  array:any[]=[{}]
    this.data.forEach(x=>{
      let row=0;
      while (this.array[row]["day"+x.day])
      {
          row++
          if (!this.array[row])
             this.array[row]={}
      }

      this.array[row]["day"+x.day]=x
    })

And create the table like

<table>
  <th *ngFor="let keyPair of array[0]|keyvalue">{{keyPair.key}}</th>
  <tr *ngFor="let item of array;let i=index">
    <td *ngFor="let keyPair of array[0]|keyvalue">
      {{item[keyPair.key]?.value}}
    </td>
    </tr>
</table>

See stackblitz

Eliseo
  • 50,109
  • 4
  • 29
  • 67