-1

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.

asked May 8, 2018 at 15:00
2
  • You can use Angular Data Table for this. Commented May 8, 2018 at 15:03
  • You can check a tutorial here: codeburst.io/… Or use an existing module with data tables implemented. Commented May 8, 2018 at 15:03

1 Answer 1

2

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.

answered May 8, 2018 at 15:06
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.