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

Dev error occurs due to a change in Angular2 pipe causing the message "has changed after it was checked"

I understand the reason for this error being thrown, but I am struggling with organizing my code to resolve it. Here is the problem: @Component({ selector: 'article', templateUrl: 'article.html', moduleId: module.id, di ...

How to apply a unique background color in Angular Material version 17

I am in the process of developing an Angular application using Angular Material 17. My query resembles that of Angular Material2 theming - how to set app background?, but the solutions suggested there are not applicable to me, likely due to my utilization ...

Tips for creating unique names for JSON data modification functions

I have some data stored in JSON format that I need to slightly rearrange before sending it to the client. What should I name the function responsible for this reordering? Is serializeSomething a suitable choice? From what I understand, serialization invo ...

Sending a POST request to WebAPI2

Currently, I am in the process of developing a REST service using WebAPI2. One of the tasks at hand is to add a new book to the database. Below is the structure of my Book model: public class Book { public int Id { get; set; } public string Name { ge ...

Obtain a filtering dropdown list directly from the database within Ag-grid

Currently in my interface, I am attempting to implement a filter for the FOLDER column. This filter is supposed to retrieve data from the database and present it in a dropdown checkbox within that column. The filtering should be based on the selected data. ...

Pressing an ASP.NET submit button triggers a jQuery Ajax call for closing purposes

I am currently developing a webpage in asp.net that utilizes JQuery UI dialog. This dialog contains a submit button which, when clicked, closes the dialog. I am looking to incorporate a call to a Webmethod upon submission. If the method returns true, then ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

Are you facing a version issue when trying to install npm packages like [email protected] and [email protected]?

Previously, I encountered unmet dependencies in npm installation. To resolve this issue, I referred to this helpful discussion. However, now I am facing problems related to npm deprecated versions: [email protected] and [email protected] when try ...

Steps for generating a signal that postpones the primary signal and promptly resets

I am looking to create a signal that will automatically switch to an underlying signal or memo after a specific delay, and reset immediately if the primary signal is cleared. The code snippet below illustrates my desired functionality. import { render } fr ...

How to include extra data in Angular Firebase user creation using the createUserWithEmailAndPassword

Currently, I am working on implementing the Firebase createUserWithEmailAndPassword method. However, I would like to include an additional field named 'name' in Cloud Firestore. Below is a snippet of my code: auth.service.ts SignUp(email: string ...

Instructions for transforming rows into columns in JSON format

Looking to convert an array of JSON objects into a format where rows become columns and the values at the side become column values, similar to the crosstab function in PostgreSQL. The JSON data looks something like this: {"marketcode":"01","size":"8,5", ...

Tips for reorganizing the files within a directory using Visual Studio Code

Is there a way to reformat an entire project folder at once, rather than just one document? I know that I can use the shortcut key Alt+Shift+F or right click on a document and select Format Document. My projects consist of Typescript files in the Angular ...

Encounter a Config validation error while trying to utilize Nest.js ConfigService within e2e tests

I'm encountering an error despite having the NODE_ENV=development variable in my .env file. The error message reads: ● Test suite failed to run Config validation error: "NODE_ENV" must be one of [development, production] 11 | imports ...

Guide on utilizing "setFont" in jsPDF with UTF-8 encoding?

Currently working on a project using Angular 7 I am trying to incorporate a custom font (UTF-8) into my PDF generation service using jsPDF. Despite researching various examples, none seem to work for me. The documentation on the jsPDF GitHub page mentions ...

What causes a TDictionary to malfunction after deserialization?

My attempt to serialize and deserialize a standard Delphi container using the standard Delphi serializer has encountered some issues. procedure TForm7.TestButtonClick(Sender: TObject); var dict: TDictionary<Integer, Integer>; jsonValue: TJSO ...

Is it possible to incorporate a timer function within a data grid using React Material-UI framework?

Trying to implement a timer that calculates the time difference based on a timestamp retrieved from the store. The data is dynamically filled. Using React MUI (Datagrid) and struggling to get it working. Although I see the correct values in the console, ...

Processing JSON in PHP after an AJAX POST request

In the scenario where JavaScript is used to make an ajax request: index.js- var dataFeedback = $("#feedback_popup_message_body").val(); var jsonObj = JSON.stringify({dataFeedback: dataFeedback}); $.ajax({ url: "index.php", type: 'POST' ...

Using Django to Display a Line Chart with Data from a Dictionary in a Template

I have a dictionary that was generated in the views.py file. The structure of the dictionary is as follows, but it contains data for an unspecified number of enterprises: { enterprise1: {'Year': ['2014/2015', '2016/2017', &ap ...

The shop named 'someStore' is currently unavailable! Please ensure that it is being offered by a valid Provider

I'm having trouble setting up a new project using React, Typescript, and MobX. Despite having a relatively simple piece of code, I can't seem to get MobX to work properly. It keeps showing me this error message: Uncaught Error: MobX injector: S ...

Issue with D3: Events not triggering transitions

I am currently working on creating a bar chart using D3 in Angular4. // Enter Phase this.chart.selectAll('.bar') .data(this.barData) .enter() .append('rect') .attr('class', 'bar'); // Update Phase let bars ...