Is it possible to create a dynamic Table(dynamic Columns) based on a JSON object with Angular 5 directives/ Or with the help of jQuery? If so how?
Lets say i get this JSON response from a REST API:
{
name: "Ferrari"
country: "Italy",
creater: "Enzo Ferrari"
cars: [
{
modell: "Ferrari 488",
price: "215.683€"
},
{
modell: "Ferrari Portofino",
price: "189.704€"
}
]
}
Now i want to create a Table out of this Data that should look like this:
+-----------+----------+--------------+--------------+------------+--------------------+-------------+
| Name | Country | Creater | Modell | Price | Modell | Price |
+-----------+----------+--------------+--------------+------------+----------------------------------+
| Ferrari | Italy | Enzo Ferrarie| Ferrarie 488 | 189.704€ | Ferrarie Portofino | 189.704€ |
+-----------+----------+--------------+--------------+------------+--------------------+-------------+
What would the best approach be to solve this? I just cant figure it out how to solve this problem? Any help is really appreciated.
-
You can use Angular Data Table for this.Nicolas– Nicolas2018年05月08日 15:03:32 +00:00Commented May 8, 2018 at 15:03
-
You can check a tutorial here: codeburst.io/… Or use an existing module with data tables implemented.Krypt1– Krypt12018年05月08日 15:03:40 +00:00Commented May 8, 2018 at 15:03
1 Answer 1
If you only have one object in the table (meaning one header row and one data row) you could do something like this:
<table>
<thead>
<tr>
<th>Name</th>
<th>Country</th>
<th>Creater</th>
<ng-template ngFor [ngForOf]="data.cars">
<th>Modell</th>
<th>Price</th>
</ng-template>
</tr>
</thead>
<tbody>
<tr>
<td>{{ data.name }}</td>
<td>{{ data.country }}</td>
<td>{{ data.creater }}</td>
<ng-template ngFor let-car [ngForOf]="data.cars">
<th>{{ car.modell }}</th>
<th>{{ car.price }}</th>
</ng-template>
</tr>
</tbody>
</table>
You can us ng-template and the ngFor directive to loop over the cars.
Important: If you have multiple data rows you need to make sure to transform your data so you always display the same amount of columns, otherwise the html will be broken.
Comments
Explore related questions
See similar questions with these tags.