I want to create a table with dynamically generated columns. I used PrimeNg library for the grid.
I opened many questions,but no one replied me,please help me to do this.
I used with *ngFor to generate table column headers
There are 2 arays. one for the row data and one for columns names.
Here is my row data array.which contains one row
uersSurveyAnswers: any = [
{
userEmail: 'amara@gmail.com',
qustns: [
{
qNo: 1,
ansrs: ['1']
},
{
qNo: 2,
ansrs: ['1', '0', '1', '1']
},
{
qNo: 5,
ansrs: ['2']
},
{
qNo: 6,
ansrs: ['0', '1', '1', '0']
}
]
}];
Columns to data should be load below wise
column Q1.1 - > uersSurveyAnswers -> qustns[0].ansrs[0]
column Q2.1 - > uersSurveyAnswers -> qustns[1].ansrs[0]
column Q2.2 - > uersSurveyAnswers -> qustns[1].ansrs[1]
column Q2.3 - > uersSurveyAnswers -> qustns[1].ansrs[2]
column Q2.4 - > uersSurveyAnswers -> qustns[1].ansrs[3]
column Q5.1 - > uersSurveyAnswers -> qustns[2].ansrs[0]
column Q6.1 - > uersSurveyAnswers -> qustns[3].ansrs[0]
column Q6.2 - > uersSurveyAnswers -> qustns[3].ansrs[1]
column Q6.3 - > uersSurveyAnswers -> qustns[3].ansrs[2]
column Q6.4 - > uersSurveyAnswers -> qustns[3].ansrs[3]
Here is my html code
<p-table [columns]="columns" [value]="uersSurveyAnswers">
<ng-template pTemplate="header" let-columns>
<tr>
<th>
Respondent Name
</th>
<th *ngFor="let col of columns">
{{col.header}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-surveyAnswer let-columns="columns">
<tr>
<td>{{surveyAnswer.userEmail}}</td>
<td>{{surveyAnswer.qustns[0].ansrs[0]}}</td>
<td *ngFor="let col of columns">
{{col.field}}
</td>
</tr>
</ng-template>
</p-table>
Here is my columns array
columns = [
{
field: 'qustns[0].ansrs[0]',
header: 'Q1.1'
},
{
field: 'qustns[1].ansrs[0]',
header: 'Q2.1'
},
{
field: 'qustns[1].ansrs[1]',
header: 'Q2.2'
},
{
field: 'qustns[1].ansrs[2]',
header: 'Q2.3'
}
,
{
field: 'qustns[1].ansrs[3]',
header: 'Q2.4'
}
,
{
field: 'qustns[2].ansrs[0]',
header: 'Q5.1'
}
,
{
field: 'qustns[3].ansrs[0]',
header: 'Q6.1'
}
,
{
field: 'qustns[3].ansrs[1]',
header: 'Q6.2'
}
,
{
field: 'qustns[3].ansrs[2]',
header: 'Q6.3'
}
,
{
field: 'qustns[3].ansrs[3]',
header: 'Q6.4'
}]
this array is generated by dynamically.
Now my problem is, inside my second 'ng-template' tag contains let-surveyAnswer which contains the row data.
If I create column with
<td>{{surveyAnswer.qustns[0].ansrs[0]}}</td>
Then it's showing the row data
but I can't understand how to do this in html like below
<td *ngFor="let col of columns">
{{col.field}}
</td>
col.field contains columns array data like
qustns[0].ansrs[0]
I want to get the data like below
<td *ngFor="let col of columns">
{{surveyAnswer.col.field}}
</td>
Here is Stackblitz url https://stackblitz.com/edit/angular-ggvf31
Please tell me how to do this.