Dynamic build a table from json data in angular2 - json

I can't wrap my head around a looping system I need to make to build up a table from json data. This is what I've got so far (tried some other stuff but I think this illustrates it the best way).
Looping through the headers works fine, it's just the cells I can't get to work.
This is my dummy data:
tableMockData = [
{
"header": "TH 1",
"rows": [
"TH1 - row1",
"TH1 -row2",
"TH1 - row3",
"TH1 - row4"
]
},
{
"header": "TH 2",
"rows": [
"TH2 -row1",
"TH2 - row2",
"TH2 - row3",
"TH2 - row4",
]
},
{
"header": "TH 3",
"rows": [
"TH3 -row1",
"TH3 - row2",
"TH3 - row3",
"TH3 - row4",
]
},
{
"header": "TH 4",
"rows": [
"TH4 - row1",
"TH4 - row2",
"TH4 - row3",
"TH4 - row4",
]
}
]
This is my basic loop as starting point:
<tr *ngFor="let row of tableMockData; let i = index">
<td>{{row.rows[i]}}</td>
</tr>
This is my outcome:
This is my desired outcome:
Can someone point me out in the right direction, I know which cell needs to go where but I simply can't wrap my head around how to loop through it.
Thanks
Update:
here is a stackblitz example:
https://stackblitz.com/edit/angular-cdoqwb

Update your Html with below code
<table>
<tr>
<th *ngFor="let row of tableMockData; let i = index">{{row.header}}
</th>
</tr>
<tr *ngFor="let row of tableMockData; let i = index">
<td *ngFor="let row1 of row.rows">
{{row1}}
</td>
</tr>
</table>
You do not properly bind your JSON.

Related

Angular: Dynamically find headers when converting JSON array to HTML table

In Angular, I want to convert a JSON array to an HTML table.
I have seen an old answer for AngularJS:
<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>
JSON looks like this:
[{
"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've tried to translate it to the Angular syntax. Here is what I got so far:
<table>
<thead>
<tr>
<th *ngFor="let item of records[0] | keyvalue">{{item.key}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of records">
<td *ngFor="let item1 of item | keyvalue">
{{item1.value}}
</td>
</tr>
</tbody>
</table>
Right now it's failing to compile because records[0] is undefined... how can I translate this expression to the newer syntax (or create something equivalent)?
UPDATE 1:
I have a partial solution. However with this partial solution the rendered table is not completely identical to the older AngularJS rendition (because it creates multiple unnecessary header rows, which only one of them is populated, as opposed to only one header row in the older rendition).
<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>
Do you have a better way to do it, possibly similar to the older AngularJS version?
UPDATE 2:
In Angular, I access the JSON data through a request from Angular that is then redirected to a back end service. That service may read a file, or get the data from a database. When the back end service has the data ready, it returns the data to the Angular request. The code on the Angular end looks like this:
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, {});
}
I think maybe you need to define records in the component.
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"
}];
I am fairly certain this is what you need: https://stackblitz.com/edit/angular-ivy-n7irpw?file=src/app/hello.component.ts
Take a look at how I import the file in the app.component.ts
As well as how I loop in the HTML.
Let me know if it helps!

How to iterate a JSON array in typescript in HTML?

I have a snippets of JSON array as shown below:
[{
"auction_number": "015",
"email": "pete#abc.com",
"first_name": "Peter",
"last_name": "Dan",
"table": 0,
"id": "015"
},
{
"auction_number": "024",
"email": "dan#gog.com",
"first_name": "Dan",
"last_name": "Fain",
"table": 0,
"id": "024"
}
]
Typescript Code:
The typescript (ts) for the above JSON array is shown below. Here attendees is an array object.
attendees: Attendee[];
constructor(public authService: AuthService) {
const str = localStorage.getItem("attendees");
if(str) {
this.attendees = JSON.parse(str);
console.log(str);
}
}
HTML Code:
The HTML code which I have used in order to iterate everything from the JSON array (in the typescript code) is shown below. For some reasons, it is not able to iterate attendees in the HTML.
<tr *ngFor="let row of attendees">
<td class="left">{{ attendees.first_name }} {{ attendees.last_name }}</td>
<td class="number1">250</td>
<td class="table1">{{attendees.table}}</td>
<td class="right-bill">Bill</td>
</tr>
Problem Statement:
I am wondering what changes I should make in the HTML code above so that I am successfully able to iterate attendees array. I tried using ngfor directive but somehow it didn't work.
You should reference fields in each row as row.first_name because you set each attendee as let row of attendees. The variable you defined is row.
You are accessing the parent loop again, you should access only the elements of row
<tr *ngFor="let row of attendees">
<td class="left">{{ row .first_name }} {{ row .last_name }}</td>
<td class="number1">250</td>
<td class="table1">{{attendees.table}}</td>
<td class="right-bill">Bill</td>
</tr>

Jade - How to create table with checkbox

How to create this code in jade template?
<table>
<tr>
<th>#</th>
<th><input type="checkbox"></th>
<th>User</th>
</tr>
<tr>
<td>1</td>
<td><input type="checkbox"></td>
<td>haacki47</td>
</tr>
I use compiler gulp-jade
I try to use
each val in ["#","<input type='checkbox'>","User"]
But i getting error :=(
A multidimensional array should solve your problem ?
Also instead of passing a HTML inside the data, it is better to handle it in Jade
- var datas = [
- {
- index: "#",
- input: "checkbox",
- name: "user"
- },
- {
- index: "1",
- input: "checkbox",
- name: "haacki47"
- }
- ];
table
each data in datas
tr
td=data.index
td
case data.input
when "checkbox"
input(type="checkbox")
td=data.name
Codepen : http://codepen.io/Pototo/pen/mVeRwm

How to iterate through a list which is in another list in thymeleaf?

I'm new in thymeleaf. i'm stuck in one place where i need to iterate through a list of strings which is present inside another list. For example, ihave a json like this :
{
"_id" : ObjectId("54e1865423asgj086"),
"Name" : "Carbon Utility",
"Modified In " : "DEC 5th",
"Imported" : "N",
"Classification" : "Functional SW delivery",
"Type Designation" : "Heavy Use",
"StateList" : [
{
"name" : "Create",
"currentStatus" : "False",
"stateDuration" : "336264 "
},
{
"name" : "Implement",
"currentStatus" : "False",
"stateDuration" : "1393827 "
},
{
"name" : "RampUp",
"currentStatus" : "False",
"stateDuration" : "34 "
},
]
}
in my Controller, i'm adding this to a object.
#RequestMapping(value = "/Search1", method = RequestMethod.GET)
public String showEntity( #RequestParam("type") String typeNameid,Model model,HttpSession session) {
------ my other stuffs--------
---- here i'm getting data from other html and spliting to add to model----
model.addAttribute("resultSourceDbObject",migrationSourceDataBean.getResultSourceDbObject());
return "wipdm/Display";
}
Now, in my html page. I'm able to print the id,name and type desgination. but i'm stuck in iterating through the statelist. For each statelist i have to create a separate subfolder inside a table and need to display the name,status and duration. I'm trying this but not working.
<table id="example-advanced" class="table table-striped table-bordered table-hover" style=" font-size:1.1em;">
<thead class="dark-border-bottom">
<tr>
<th style="text-align:center"> Key</th>
<th style="text-align:center">Values</th>
</tr>
</thead>
<tbody>
<tr data-tt-id='1'><td><span class="file"> Type</span></td><td><span th:text="${resultSourceDbObject.getString('Type Designation')}"></span> </td></tr>
<tr data-tt-id='1'><td><span class="file"> Name</span></td><td><span th:text="${resultSourceDbObject.getString('Name')}"></span> </td></tr>
<tr data-tt-id='1'><td><span class="file"> id</span></td><td><span th:text="${resultSourceDbObject.getString('_id')}"></span> </td></tr>
<tr data-tt-id='2'><td><span class='folder'>Statelist</span></td><td></td></tr>
<tr data-tt-id='2-1' data-tt-parent-id='2' th:each="relresult : ${resultSourceDbObject.getString('StateList')}"><td><span class='folder' th:text="Relationship" >Relationship</span></td><td>Folder</td></tr>
<tr data-tt-id='2-1-1' data-tt-parent-id='2-1'><td><span class='file' >name</span></td><td th:text="${relresult.getString('name')}">Release</td></tr>
<tr data-tt-id='2-1-2' data-tt-parent-id='2-1'><td><span class='file'>currentstatus</span></td><td th:text="${relresult.getString('currentStatus')}">132456424</td></tr>
<tr data-tt-id='2-1-3' data-tt-parent-id='2-1'><td><span class='file'>Stateduration</span></td><td th:text="${relresult.getString('stateDuration')}">16572464</td></tr>
</tbody>
</table>
Can anybody tell me where i'm going wrong and how to acheive this.? Thanks in advance.
I'm not sure exactly what type of object migrationSourceDataBean.getResultSourceDbObject() is returning, but resultSourceDbObject.getString('StateList') won't be returning what you need. (I guess it's just giving you the JSON?)
Assuming it's something similar to JSONObject you should be calling getJSONArray() (or similar) which will give you the nested list which you can then iterate over.

Iterating through JSON data with Mustache JS

I have been trying and failing to iterate through some JSON Data with Mustache JS in order to populate a table which looks like:
{
"Pay":[
[
"Regular Hours",
"$75.00",
"$75.00"
]
],
"Earnings":[
[
"Regular Earnings",
"$2,277.00",
"$1,200.00"
],
[
"Non Tax Vacation Pay",
"$0.00",
"$50.80"
]
],
"Deductions":[
[
"Other Deduction 5",
"$0.00",
"$50.00"
]
]
}
How would I iterate using Mustache JS in order to have every inner array as rows and the outer array as headers like this:
<tr>
<th colspan="4">Pay</th>
</tr>
<tr>
<td>Regular Hours</td>
<td>75</td>
<td>75</td>
</tr>
<!-- Etc. -->
Any help would be greatly appreciated
This issue has made me consider switching over to handlebars to avoid the need for hacky code. The data being passed in is the JSON input from the original question. This function will format the data into key value pairs, after which the data is rendered by the Mustache template.
function (data) {
var payslipList = JSON.parse(data.d);
formattedData = { 'entries': [] };
for (var property in payslipList) {
if (payslipList.hasOwnProperty(property)) {
formattedData['entries'].push({
'key': property,
'value': payslipList[property]
});
}
}
var tablePayslip = $("#tblPayDetails tbody");
$.each(formattedData, function (id, payslip) {
var template = $('#renderPaystub').html();
var html = Mustache.render(template, payslip);
tablePayslip.append(html);
});
The template to access the key value pairs would look something like this:
<script type="text/template" id="renderPaystub">
{{#.}}
{{#.}}
<tr>
<th colspan="3">{{key}}</th>
</tr>
{{/.}}
{{#value}}
<tr>
{{#.}}<td>{{.}}</td>{{/.}}
</tr>
{{/value}}
{{/.}}
</script>
This template is fairly ugly and ambiguous, if there is a better method to achieve this, feel free to let me know.