Tips for generating a JSON-driven table in Angular 2

I'm attempting to build a dynamic datagrid in angular2 using a JSON object as the source. The challenge I face is not knowing the structure of the columns within the table, making it difficult to render the rows properly.

My understanding is that I need to define the row structure in order to render the cells, but without knowledge of the column names, this becomes problematic.

Let me illustrate with examples...

Below are two JSON examples that need to be displayed in the same table:

Example 1

{
  "table": {
    "columns": {
      "column": [
        {
          "-articleColumn": "articleCode",
          "-label": "Article Code ",
          "-fCode": "f9",
          "-value": "column1"
        },
        {
          "-articleColumn": "Article.trend",
          "-label": "Trend ",
          "-fCode": "f25",
          "-value": "column2"
        }
      ]
    },
    "rows": {
      "row": [
        {
          "column1": "articleCode",
          "column2": "Avg"
        },
        {
          "column1": "151110103",
          "column2": "100"
        },
        {
          "column1": "151110109",
          "column2": "101"
        },
        {
          "column1": "151110111",
          "column2": "102"
        },
        {
          "column1": "151110117",
          "column2": "103"
        }
      ]
    }
  }
}

Example 2

{
  "table": {
    "columns": {
      "column": [
        {
          "-articleColumn": "articleCode",
          "-label": "Article Code ",
          "-fCode": "f9",
          "-value": "column1"
        },
        {
          "-articleColumn": "Article.trend",
          "-label": "Trend ",
          "-fCode": "f25",
          "-value": "column2"
        },
        {
          "-averageDemand": "Article.averageDemand",
          "-label": "Average Demand ",
          "-fCode": "f564",
          "-value": "column3"
        },
        {
          "-warehouse": "Article.warehouse",
          "-label": "Warehouse ",
          "-fCode": "f295",
          "-value": "column4"
        }
      ]
    },
    "rows": {
      "row": [
        {
          "column1": "151110103",
          "column2": "100",
          "column3": "500",
          "column4": "TOT"
        },
        {
          "column1": "151110109",
          "column2": "101",
          "column3": "46",
          "column4": "TOT"
        },
        {
          "column1": "151110111",
          "column2": "102",
          "column3": "16",
          "column4": "SEL"
        },
        {
          "column1": "151110117",
          "column2": "103",
          "column3": "112",
          "column4": "SEL"
        }
      ]
    }
  }
}

Components used...

The Table Component:

<table class="mdl-data-table mdl-js-data-table  mdl-shadow--2dp">
    <tbody>             
        <app-field-mapping-row [rowData]="row"  *ngFor="let row of rows"></app-field-mapping-row>
    </tbody>
</table> 

app-field-mapping-row component:

I am stuck at this point!

<tr>
  <td class="mdl-data-table__cell--non-numeric" *ngFor="let cell of rowData" >
    {{cell}}
 </td>
</tr>

How can I dynamically create the cells and iterate through the row's children which have different names each time... If all children were named 'cell', I could use an array, but since they vary, I don't know how to loop through them.

I have yet to discover a method to convert the 'children' of a JSON node into an array...

eg. *ngFor="let cell of rowData.children()"

Your assistance is always appreciated.

Answer №1

Check out my AngularJS implementation below. The second JSON data you provided is missing quite a few commas.

Here's how my view looks:

<table class="table table-striped table-hover display" style="cellspacing:0;width:100%">
       <thead>
            <tr>
               <th ng-repeat="columns in tableData.table.columns.column">
                   {{columns.label}}
                </th>
            </tr>
       </thead>

     <tbody >
           <tr ng-repeat="row in tableData.table.rows.row"> 
                <td ng-repeat="(key,val) in row">{{val}}</td> 
           </tr>
    </tbody>
</table>   

I made some adjustments to your JSON by removing hyphens from the labels and fixing the overall format. Here's the updated JSON:

{
  "table": {
    "columns": {
      "column": [
        {
          "articleColumn": "articleCode",
          "label": "Article Code",
          "fCode": "f9",
          "value": "column1"
        },
        {
          "articleColumn": "Article.trend",
          "label": "Trend",
          "fCode": "f25",
          "value": "column2"
        },
        {
          "averageDemand": "Article.averageDemand",
          "label": "Average Demand",
          "fCode": "f564",
          "value": "column3"
        },
        {
          "warehouse": "Article.warehouse",
          "label": "Warehouse",
          "fCode": "f295",
          "value": "column4"
        }
      ]
    },
    "rows": {
      "row": [
        {
          "column1": "151110103",
          "column2": "100",
          "column3": "500",
          "column4": "TOT"
        },
        {
          "column1": "151110109",
          "column2": "101",
          "column3": "46",
          "column4": "TOT"
        },
        {
          "column1": "151110111",
          "column2": "102",
          "column3": "16",
          "column4": "SEL"
        },
        {
          "column1": "151110117",
          "column2": "103",
          "column3": "112",
          "column4": "SEL"
        }
      ]
    }
  }
}

To summarize, I repeat columns for the thead section to display labels and repeat rows followed by columns within tbody using val and key.

Check out the jsFiddle link for the code snippet: http://jsfiddle.net/noitse/Lvc0u55v/9487/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

Issue with jQuery's $(this).serialize() function not functioning correctly

&cellphone=0400000000¬es=this+is+a+test The mistake is visible above You'll notice that the following error has occurred ¬es It was actually supposed to be &notes= I'm curious why this happened. Below is the HTML form: <!---lef ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

Tips on including starting information into an angularjs application from the displayed HTML

I'm currently working on a complex AngularJs application that requires User Login. Once the user is authenticated, a page will be displayed to them and additional data will be loaded later. There are two methods for achieving this: XHR Fetch af ...

What is the best way to create a MySQL query using the JSON data provided?

Here is the example data that is being sent to the PHP script: [{"id":1,"due_date":"2011-09-03","due_amount":"48279.00","wo_interest":"45980.00"}, {"id":2,"due_date":"2011-10-03","due_amount":"48279.00","wo_interest":"45980.00"}] The table fields are in ...

Error encountered while attempting to load an image in a React component using TypeScript linting

I am currently working on a React app with Next.js where I have imported an image using the following code: import image1 from '../../../img/dummy-image-2.jpg'; Subsequently, I use the image in my app like so: <img src={image1} alt="Dumm ...

Sending JSON data stored in $scope using AngularJS with AJAXPOST request

I am frustrated: I am currently working on an AngularJS project and struggling to correctly post data. I have filled out some HTML input fields, with values stored in a variable like $scope.product, and now I need to send this JSON structure of $scope.pro ...

You will need to return a string instead of a Json Object in order for it to function correctly

I am facing an issue where I need to return a list of json objects to the view, but it seems to be causing problems because it's being returned as an object. It works fine if I return a string or a list of strings instead. However, what I really need ...

Make an Angular 2 request to a particular website

I have a service within my project named user.service.t.js. I am trying to send a request to a specific site, such as sites.com, in order to retrieve its content. Below is the code snippet that outlines how I am attempting to do this: getSites(user) { ...

Retrieve the file from the REST API without using the window.open method

I'm looking for a method to download files from an API without using window.open(). I want the download process to start immediately upon calling the API. Currently, I am downloading an .xls file generated by a REST API using window.open() API Endpo ...

How to vertically align Material UI ListItemSecondaryAction in a ListItem

I encountered an issue with @material-ui/core while trying to create a ListItem with Action. I am looking for a way to ensure that the ListItemSecondaryAction stays on top like ListItemAvatar when the secondary text becomes longer. Is there any solution to ...

Unable to resolve the FormGroup when using the FormBulider

Currently, I am facing an issue while working with FormBuilder and FormGroup in Angular 2. When I try to submit a form, the form.value that is passed is of type FormGroup. After trying to access my properties and then restarting the lite server, the app f ...

Is there a way to verify the availability of an authenticated resource without triggering a pop-up for credentials in the browser?

I am facing the challenge of fetching data from a web service located on a different server without knowing if the user has an active session on that server. If the user does have a session, I want to retrieve the data automatically. However, if they do no ...

Tips for Formatting Dates as ISO-8601 in Java

I am attempting to convert the standard ISO 8601 format 2014-09-11T21:28:29.429209Z into a more readable MMM d yyyy hh:mm z format, but unfortunately my current code is not producing the desired result. public void setCreatedAt( String dateTime ) { L ...

Troubleshooting tip: The request body is missing and needs to be added to resolve the issue

I am encountering an issue while trying to update a boolean column in my database for approving customer accounts using an angular front-end button. Whenever I send the request, my controller throws an error stating Resolved [org.springframework.http.conve ...

Enhance constructor functionality in Ionic 4 by incorporating additional parameters

Recently, I started using Ionic and came across a location page. In the location/location.page.ts file, there was an automatically generated empty constructor like this: constructor() { } Initially, the page functioned properly with this setup. However, ...

Develop an application using ASP.NET MVC that allows for returning a JavascriptResult along with a

Imagine this situation When using MVC, it is quite simple to send a Javascript code back to the client for execution public ActionResult DoSomething() { return JavaScript("alert('Hello world!');"); } On the client side, ...

Converting JSON HTTP response to an Array in AngularJS 2: A Comprehensive Guide

As I work on a Http get request in Angular 2, the response returned is in JSON format. However, I am facing an issue when trying to use it in a ngFor loop because it is not formatted as an Array. Is there a way to convert JSON data to an Array in Angular ...

Announcing the outcomes I received from JSON notifications

Hey there, I need some assistance. Here's the deal - whenever a user enters something into a text field and then clicks out of it, an ajax request is triggered. $(document).ready(function() { //On Focus lose get content of the first input field $(&ap ...

Is there a way to update JSON data through a post request without it getting added to the existing data?

Hello, I am currently delving into Angular2 and encountering a problem concerning RestAPI. When I send a post request to the server with a JSON file, I intend to update the existing data in the JSON file; however, what actually happens is that the new data ...