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, {});
}