Creating HTML tables from JSON arrays dynamically in Angular using headers auto-detection

Is there a way in Angular to convert a JSON array into an HTML table?

I came across an old answer for AngularJS, but I'm looking for a solution that works in Angular:

<table>
    <thead>
      <tr>
        <th ng-repeat="(key, value) in records[0]">{{key}}</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="(key, value) in records">
        <td ng-repeat="(key, value) in value">
          {{value}}
        </td>
      </tr>
    </tbody>
</table>

This is what my JSON data looks like:

[{
    "Name": "Alfreds Futterkiste",
    "City": "Berlin",
    "Country": "Germany"
}, {
    "Name": "Berglunds snabbköp",
    "City": "Luleå",
    "Country": "Sweden"
}, {
    "Name": "Centro comercial Moctezuma",
    "City": "México D.F.",
    "Country": "Mexico"
}]

I have attempted to translate the AngularJS syntax to Angular. However, it's throwing an error because records[0] is undefined. Can someone help me with creating an equivalent expression using newer Angular syntax?

UPDATE 1:

I managed to create a workaround, but it's not producing the exact same output as the old AngularJS version. It generates extra header rows instead of one populated header row.

<table style="border-collapse: collapse;">
    <thead *ngFor="let item of records; let last=last">
      <tr *ngIf="last">
        <th *ngFor="let item1 of item | keyvalue">
          {{item1.key}}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of records">
        <td *ngFor="let item1 of item | keyvalue">
          {{item1.value}}
        </td>
      </tr>
    </tbody>
</table>

Does anyone know of a better approach, similar to the older AngularJS method?

UPDATE 2:

In Angular, I retrieve JSON data through a request sent from Angular to a backend service. The backend service may fetch the data from a file or database. Once the data is ready, it is returned to the Angular request. Here is an excerpt of the code on the Angular side:

  HTML:

  <div>
    <h3>Test Post Request</h3>
    <button (click)="postData()">Click Me</button>
    <div>Response: {{records}}</div>
  </div>

  TypeScript:

  private dataPostTestUrl = '/api/postTest';
  records: string | undefined;

  public postData(): void {
    this.appService.sendData().subscribe((data: any) => {
      this.records = data.content;
    });
  }

  public sendData(): Observable<any> {
    return this.http.post(this.dataPostTestUrl, {});
  }

Answer №1

It seems like defining records within the component could be beneficial.

records = [{
    "Name": "Alfreds Futterkiste",
    "City": "Berlin",
    "Country": "Germany"
}, {
    "Name": "Berglunds snabbköp",
    "City": "Luleå",
    "Country": "Sweden"
}, {
    "Name": "Centro comercial Moctezuma",
    "City": "México D.F.",
    "Country": "Mexico"
}];

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

Guide on dynamically injecting a helper class

Within my component, I am utilizing two different helper classes as shown below: import {HelperA} ... import {HelperB} ... ... @Component({..}) export class MyComponent implements OnInit { helper: Helper; constructor(private ref: ElementRef, ...

Trouble arises with tap operator's output in RxJS

I'm puzzled by the results of the code below. According to the take(3) function, processing should stop after rendering 10, but I'm still seeing 5, 6, and 9 from the tap operator. Please see the output and code snippet below for reference. Tapp ...

Access real-time information directly from the database

Looking to dynamically update an unordered list in real-time. Imagine having an unordered list where each item is displayed in order from newest to oldest. I am searching for a way to regularly check the server for updates and seamlessly integrate those u ...

How to update a value in a JSON object using Node.js Express

Hello there, I am new to NodeJS Express and I have a question about how to change the date format in the response JSON. I would like to convert the date format from "2017-12-14T05:23:01.000Z" to "dd/mm/yyyy". Specifically, I want the date value under the k ...

Implementing ETag in Angular 2

Implementing the odata standard which utilizes ETag has presented a challenge for me, particularly with PATCH requests. Each PATCH request requires sending the ETag in the header as If-None-Match. A HTTP status of 200 indicates that the change was successf ...

The gridOptions.$gridScope.columns in ng-grid is modified two times when hiding or showing columns

Question: Why does the $scope.$watch function get called twice when I manually hide/show a column but only once when I reorder/sort columns in ng-grid? When I specifically target a single column with the watch function, it is only called once. I suspect ...

What is the best way to parse this JSON structure using restsharp in c#?

What is the best way to structure my classes in order to successfully deserialize the JSON data provided below? { "Bob": [{ "code": "Bob", "tier": 1 }, { "code": "Bob", "tier": 2 ...

Display JSX using the material-ui Button component when it is clicked

When I click on a material-ui button, I'm attempting to render JSX. Despite logging to the console when clicking, none of the JSX is being displayed. interface TileProps { address?: string; } const renderDisplayer = (address: string) => { ...

Execute the function right away and then at regular intervals of X seconds

Need help with Angular 7 function call timing checkData(): Observable<string> { return this.http.get('') .pipe( map(res => { let result; result = { packageNumbe ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

Is it possible to execute Protractor on a browser without a specific WebDriver setup?

I'm in the process of setting up end-to-end tests for a cutting-edge AngularJS web application. My goal is to run these tests on a device that operates with a less common WebKit-based browser that does not have its own WebDriver implementation. Curren ...

Efficiently bundling Angular templates using Grunt and Browserify

I am currently utilizing angular1 in conjunction with browserify and grunt to construct my application. At present, browserify only bundles the controllers and retrieves the templates using ng-include through a separate ajax call. Due to the excessive amo ...

I am confused as to why my PHP array is being stored in MongoDB as an object and then returned as an associative array with stringified keys

Description: Within the application I am developing, there is a class dedicated to handling specific data operations. This class has functions for initializing, manipulating data in various ways, and saving changes back to a MongoDB collection. The goal i ...

Retrieving the necessary data from my object to perform a sum calculation in angular

Having trouble retrieving an attribute from an array in my code. In my .ts file, I am fetching data from my backend endpoint like this: export class PostFeedComponent implements OnInit { data: any = {}; constructor(private http: HttpClient) { t ...

Using HTML to format Microsoft Teams cards

What I have are Microsoft Teams chat messages obtained through an API that I wish to showcase on a website. The issue arises when these chat messages contain JSONs of cards. I attempted to display adaptive cards using the Adaptive Card JS SDK, and it succe ...

What is the best way to ensure that all components can access and utilize the same instance of API

Is there a way to retrieve data from the database using an API when the application starts and then release it once the app is closed, ensuring that the same data instance is available for each component? ...

Tips for concealing routes in the address bar on Angular versions 5 and above

Is it possible to conceal routes from the browser's address bar? Example: http://localhost:4200/user/profile to http://localhost:4200 Is there a way to hide routes? ...

Utilizing Angular routing: Incorporating a prefix to the child path with :ID

In my routing file, the routes are as follows: { path: 'new', component: CreateTeamComponent }, { path: ':ID-TEAM', children: [ { path: 'edit', component: EditTeamComponent }, { ...

Preventing redundant function calls in Angular's keyup event

My objective is to: Fetch data by calling a service and binding it on the ngOnit() lifecycle hook. Implement a functionality where, in a text input field, an API call is triggered only after a user stops typing for a second (debouncing between user keystr ...

Is there a way to set up a background process within electron that captures a screenshot of the entire desktop?

I'm currently working on a Desktop application using Angular2 and Electron that captures screenshots of the entire desktop and saves them to a specified path on my PC. The code for capturing screenshots is implemented in the app.component.ts file, but ...