1

I am having a problem by adding columns in table dynamically with Angular Material tables. As the table depends on an model, I have a two fixed columns (start Date , End Date) . What I want is to have a dynamic table depending on response from the server. Because the way the response coming from back end is sometimes there would be 2 columns and some times 3 and so on depending on the size of the array. My Json response is currently looks like

{
    "cars": [
        {
            "startDate": "01/11/2020",
            "endDate": "03/03/2021",
            "details": [
                {
                    "nameofThecar": "Dodge",
                    "color": "Silver",
                    "type": "Sedan"
                },
                {
                    "nameofThecar": "Nissan",
                    "color": "White",
                    "type": "micro"
                },
                {
                    "nameofThecar": "Kia",
                    "color": "blue",
                    "type": "supercar"
                }
            ]
        },
        {
            "startDate": "05/01/2020",
            "endDate": "12/05/2021",
            "details": [
                {
                    "nameofThecar": "Dodge",
                    "color": "gold",
                    "type": "SUV"
                },
                {
                    "nameofThecar": "Nissan",
                    "color": "blue",
                    "type": "MPV"
                },
                {
                    "nameofThecar": "Kia",
                    "color": "silver",
                    "type": "wagon"
                }
            ]
        }
    ]
}

I need to display the above JSON data into a table like this in Angular Mat Table

Expected Table Design

enter image description here

I tried multiple example for Angular material dynamic column. Its not working fine.

James Z
  • 12,209
  • 10
  • 24
  • 44
learntech
  • 13
  • 2

1 Answers1

0

If you are new to Angular, one approach might be just to reformat your data structure after you receive it so that it matches up better with mat-table examples - where you control the columns displayed via <tr *matHeaderRowDef=displayedColumns>. Each is unique, so you'd want to provide unique names and that should get your list going.

Another approach is to build a component that handles the array of 'details' and iterate those within the component - just display those {{x.type}} and style it so that it goes horizontal on the table row.

Voltan
  • 1,170
  • 1
  • 7
  • 16