What I'm trying to do is take a data array of objects and create a function where I can pass the data in and render the column headers and rows dynamically. Here is my sample data:
let revisions = [
{
car: {
id: 1000,
header: "Toyota"
},
revisionDate: {
header: "Revision Date",
newValue: "08/24/2021",
oldValue: "09/15/2020"
},
revisionType: {
header: "Revision Type",
newValue: "Tool Desc.",
oldValue: "Tool Number"
},
revisionNote: {
header: "Revision Note",
newValue: "Delete",
oldValue: "Delete"
},
workStation: {
header: "Garage",
newValue: "New garage",
oldValue: "Old garage"
}
}
For my function I have tried using 2 for loops, however I cannot seem to figure out how to get the properties in the array. What I've tried:
getHeaders(revisions) {
var prop;
var rowProp;
for (rowProp = 0; rowProp < revisions.length; rowProp++)
if (rowProp >= 0) {
gridData.push({ header: revisions.header });
}
for (prop = 0; prop < revisions.length; prop++) {
if (prop === "oldValue") {
gridData.push({ field: "revisionDate", header: revisions.header + " (Existing)" });
}
if (prop === "newValue") {
gridData.push({ field: "revisionDateNew", header: revisions.header + " (New)" });
}
else {
gridData.push(revisions);
}
}
return gridData;
}
Here is the html just in case:
<tr>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
Thank you for the help.
If your objects stay built the same:
{
car:{...},
revisionDate:{...},
revisionType:{...},
revisionNote:{...},
workStation:{...}
}
Then you dont even need to build a function to display that data in a table here is a table layout you could do:
<table>
<th class="row" >
<div class="col-2">{{ revisions[0].car.header }}</div>
<div class="col-2">{{ revisions[0].revisionDate.header }}</div>
<div class="col-2">{{ revisions[0].revisionType.header }}</div>
<div class="col-2">{{ revisions[0].revisionNote.header }}</div>
<div class="col-2">{{ revisions[0].workStation.header }}</div>
</th>
<td class="row" *ngFor="let rev of revisions">
<div class="col-2">{{ rev.car.id }}</div>
<div class="col-2">{{ rev.revisionDate.newValue }}</div>
<div class="col-2">{{ rev.revisionType.newValue }}</div>
<div class="col-2">{{ rev.revisionNote.newValue }}</div>
<div class="col-2">{{ rev.workStation.newValue }}</div>
</td>
</table>
revisions[0] is used to just get the first object and access the headers for display. Then after that you use your *ngFor="" in order to loop through each object and display the data within those elements.