Guide to showcasing JSON Array in an HTML table with the help of *NgFor

Struggling to showcase the data stored in an array from an external JSON file on an HTML table. Able to view the data through console logs, but unable to display it visually. Still navigating my way through Angular 7 and might be overlooking something crucial during the coding process without even realizing it.

app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/https';
import { HttpErrorResponse } from '@angular/common/https';
import { getRootView } from '@angular/core/src/render3/util';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor (private httpService: HttpClient) { }
  parameter: string;

  ngOnInit () {
    this.httpService.get('./assets/fyp2019-ff11e-export.json').subscribe(
      data => {
        this.parameter = data as string;   // FILL THE ARRAY WITH DATA.
        console.log(this.parameter);    
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );
  }


Sample content extracted from the json file:

{
  "GoogleSheet" : {
    "Data1" : {
      "LevelTankA" : 1.5,
      "LevelTankB" : 1,
      "MotorSpeed" : 15,
      "Time" : 1
    },
    "Data2" : {
      "LevelTankA" : 5,
      "LevelTankB" : 2.3,
      "MotorSpeed" : 15,
      "Time" : 2
    },
    "Data3" : {
      "LevelTankA" : 6,
      "LevelTankB" : 2.9,
      "MotorSpeed" : 20,
      "Time" : 3
    }
  }
}


section of code from component.html

  <table>
      <tr>
          <th>Tank A</th>
              <th>Tank B</th>
                  <th>Motor Speed</th>
                      <th>Time</th>        
      </tr>
      <!-- BIND ARRAY TO TABLE -->
      <tr *ngFor="let val of parameter; let i = index">   
    //prepare the key and grab the data key and values
    <td *ngFor="let obj of val">{{obj.LevelTankA | json}}</td>
    <td *ngFor="let obj of val">{{obj.LevelTankB | json}}</td>
    <td *ngFor="let obj of val">{{obj.MotorSpeed | json}}</td>
    <td *ngFor="let obj of val">{{obj.Time | json}}</td>           
      </tr>
  </table>

Encountering difficulties with binding the array to the html table. Attempted various approaches using *ngFor and *ngIf, but the data remains elusive from displaying on the screen.

Answer №1

One problem that arises is the parameter variable being of type string instead of an array:

parameter: string -> parameter: any[];

Additionally, when fetching data from the service, the response should be treated as an object.

this.httpService.get('./assets/fyp2019-ff11e-export.json').subscribe(
      data => {
        this.parameter = data;   // FILL THE ARRAY WITH DATA.
        console.log(this.parameter);    
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );

Another issue lies in the JSON file format, which should be structured like this:

{
  "GoogleSheet" : [
    "Data1" : {
      "LevelTankA" : 1.5,
      "LevelTankB" : 1,
      "MotorSpeed" : 15,
      "Time" : 1
    },
    "Data2" : {
      "LevelTankA" : 5,
      "LevelTankB" : 2.3,
      "MotorSpeed" : 15,
      "Time" : 2
    },
    "Data3" : {
      "LevelTankA" : 6,
      "LevelTankB" : 2.9,
      "MotorSpeed" : 20,
      "Time" : 3
    }
  ]
}

Furthermore, since there is a top-level object, the ngfor loop needs to be adjusted like so:

<tr *ngFor="let val of parameter.GoogleSheet; let i = index">   

Answer №2

When working on my project with Json file data.

The first step is to create a folder and a file called parameter.json

I made some modifications to your Json file as shown below

[
  {
    "LevelTankA": 1.5,
    "LevelTankB": 1,
    "MotorSpeed": 15,
    "Time": 1
  },
  {
    "LevelTankA": 5,
    "LevelTankB": 2.3,
    "MotorSpeed": 15,
    "Time": 2
  },
  {
    "LevelTankA": 6,
    "LevelTankB": 2.9,
    "MotorSpeed": 20,
    "Time": 3
  }
]

Here is the path where the file should be located:

ProjectName\src\app\pages\module\_configuration\parameter.json

Import the parameter.json in the Component

import * as parameterData from './_configuration/parameter.json';

Declare Parameter as any type like this

parameter: any;

Initialize it in ngOninit function to retrieve the data.

  ngOnInit() {
    this.parameter= <any>parameterData.default;
  }

I also made some modifications to your HTML file for better rendering of the data.

 <table>
      <tr>
          <th>Tank A</th>
              <th>Tank B</th>
                  <th>Motor Speed</th>
                      <th>Time</th>        
      </tr>
      <!-- BIND ARRAY TO TABLE -->
      <tr *ngFor="let val of parameter; let i = index">   
            <td>{{ val.LevelTankA}}</td>
            <td>{{ val.LevelTankB}}</td>
            <td>{{ val.MotorSpeed}}</td>
            <td>{{ val.Time}}</td>
      </tr>
  </table>

This solution I provided, based on my understanding, hope it helps you effectively.

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

Angular's "change" output automatically triggers input events to propagate implicitly

Encountering an unusual behavior, I have a basic component that wraps a text input: export class InplaceInputComponent { @Input() value: string; @Output() change = new EventEmitter<string>(); editedValue: string; inputChange(event: any) { ...

Contrary to GraphQLNonNull

I am currently working on implementing GraphQL and I have encountered a problem. Here is an example of the code I wrote for GraphQL: export const menuItemDataType = new GraphQL.GraphQLObjectType({ name: 'MenuItemData', fields: () => ...

What steps should I take to resolve the issue of 'unable to locate the name 'OktaAuthService' error?

I am currently trying to incorporate authentication into an Angular application using Okta. I have carefully followed the step-by-step instructions provided in the documentation at this link: . However, I am encountering an error when attempting to start t ...

Angular OAuth2 OIDC password reset process

Currently, I am integrating B2C into my Angular (8) application using angular-oauth2-oidc. I have successfully implemented sign-in and sign-out policies, as well as configuring the angular-oauth2-oidc service. However, when utilizing the standard Microsoft ...

Using Kotlin on Android to Distribute an Array/ List for Functions That Are Not Variadic

Within my program, there is a data class named: data class Entry(var name: String, var address: String, var phoneNo: String, private val amt: String, var remark: String) Alongside this class, I have a String Array: val data = arrayOf("x" ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...

Implementing Typescript for managing state in React components

Currently, I have a state set up like this: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) The structure of my InvoiceType is as follows: customer_email: string customer_name: string description: string due_date: stri ...

Is it recommended to utilize type casting for the object's toArray() method?

String[] array = c.toArray(new String[0]); Is it necessary to use a type cast here? I have seen it written as (String[])c.toArray(); and also just c.toArray() without the type cast. Which one is valid? Additionally, why do we pass new String[0] as the pa ...

How to open a new tab in Angular 2 using Angular Router navigate function

Is there a way to open a new browser tab while using router.navigate? this.router.navigate([]).then(result => { window.open(link, '_blank'); }); ...

"Organize your files with React and TypeScript using a file list

interface IVideos { lastModified: number, name: string, path: string, size: number, type: string, webkitRelativePath: string } const [videos, setVideos] = useState<IVideos[] | null>([]); <input type="file" onChange={(event) => ...

Create a line break in the React Mui DataGrid to ensure that when the text inside a row reaches its maximum

I'm facing an issue with a table created using MUI DataGrid. When user input is too long, the text gets truncated with "..." at the end. My goal is to have the text break into multiple lines within the column, similar to this example: I want the text ...

The mark-compacts were not efficient enough, they approached the heap limit and as a result, the allocation failed. The JavaScript

Currently working with Angular version 7.2 and encountering an issue when running ng serve: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory What does this error mean? How can it be resolved? The ...

What could be causing my website to lose its responsiveness after linking a domain?

Recently, I created a basic website for an event in my town using AWS Amplify from Amazon. Initially, the website was hosted without a custom domain and had a random URL. It worked well on both web and mobile platforms. However, after connecting a custom d ...

How can I effectively test the success of a form submission in next.js using jest for unit testing?

At the moment, I am in the process of developing a unit test for a registration form within my application. The main objective of this test is to ensure that the registration process can be executed successfully without actually saving any new data into th ...

Having trouble displaying the values from my Ruby array

How can I display my values using only "Puts recipe.summary? I have looped through them in "instructions" and "ingredients", but none of it appears when I "Puts recipe.summary". Could I be looping through it incorrectly? Here is my code. class Ingredie ...

The typescript-eslint-parser does not officially support this version of TypeScript

I recently acquired an outdated AngularJs application that still relies on the legacy tools: bower and grunt. Upon executing grunt serve --reload, I encounter the following warning message: WARNING: You are currently running a version of TypeScript which ...

Looping issue with ForEach in Typscript with Firebase Functions

While browsing through various questions on this topic, I've noticed that the specific answers provided don't quite fit my situation. My query involves converting a Google Firebase RTB datasnapshot into an array of custom objects, each representi ...

Error TS2339 occurs when attempting to migrate to TypeScript due to the absence of the 'PropTypes' property on the 'React' type

Currently in the process of converting a javascript/react project to a typescript/react/redux project. Encountering an issue with this particular file: import React from 'react'; import GoldenLayout from 'golden-layout'; import {Provi ...

Transferring multiple parameters between components using Navigate and ParamMap

My concern is that I'm unsure of how to pass multiple parameters through the component's route. I need to send two attributes. Is there a specific syntax required in defining the route? Below is my desired functionality for passing the attribut ...

What is the best way to save the output of an asynchronous function into a class attribute?

Currently, I am attempting to retrieve HTML content from a webpage by utilizing a class equipped with a single asynchronous method. This process involves Typescript 3.4.3 and request-promise 4.2.4. import * as rp from 'request-promise'; class H ...