I want to loop a data like ngFor
in typescript can we do the same. I'll share my code below
<table id="pdfData" *ngFor="let hubxReport of hubxReportList; let i=index">
<tr>
<th>{{hubxReport.categoryName}} "Test"</th>
</tr>
<tr>
<th>{{column}}</th>
</tr>
<tr *ngFor="let item of hubxReport.hubxDataItems">
<td></td>
<td>{{item.itemTitle}}</td>
<td>{{item.itemValue}}</td>
<td>{{item.itemUnit}}</td>
<td>{{item.normalRange}}</td>
</tr>
</table>
i want to implement the same way im looping in typescript
CodePudding user response:
In my opinion ngFor
is the easiet way to do that. Anyway Op wants to to do it in typescript. You need to go through the hubxReportList
and create a table and append some tr
and td
. Then append the table
into your body by Renderer2
.
Here is a sample that I created:
export class AppComponent {
name = 'Angular';
hubxReportList = [
{categoryName: 'nameheader', categoryvalue:'valueheader' , hubxDataItems: [{itemTitle: 'title', itemValue: 'value'}]},
{categoryName: 'nameheader1', categoryvalue:'valueheader1', hubxDataItems: [{itemTitle: 'title1', itemValue: 'value1'}]},
{categoryName: 'nameheader2', categoryvalue:'valueheader2', hubxDataItems: [{itemTitle: 'title2', itemValue: 'value2'}]},
{categoryName: 'nameheader3', categoryvalue:'valueheader3', hubxDataItems: [{itemTitle: 'title3', itemValue: 'value3'}]},
]
@ViewChild('div') div: ElementRef;
constructor (private renderer: Renderer2){
}
addElement() {
this.hubxReportList.forEach(t=> {
const table: HTMLTableElement = this.renderer.createElement('table');
table.createTHead();
var hrow = table.tHead.insertRow(0);
var cell = hrow.insertCell(0);
cell.innerHTML = t.categoryName;
cell = hrow.insertCell(1);
cell.innerHTML = t.categoryvalue;
var tbody = table.createTBody();
t.hubxDataItems.forEach(sub =>{
var row = table.tBodies[0].insertRow(0);
var c = row.insertCell(0);
c.innerHTML = sub.itemTitle;
c = row.insertCell(1);
c.innerHTML = sub.itemValue;
})
this.renderer.appendChild(this.div.nativeElement, table)
})
}