Having trouble using dynamic columns in a Primeng table? The column fields need to be in bracket notation for this setup. What if you have a column with nested JSON structure and you're not sure how to write that in bracket notation? Don't worry, we can help you out. Check out the example below:
Your JSON data:
[
{
"studentName": "test",
"email": null,
"phnNumber": 1,
"subjects": [
{
"subjectName": "Maths",
"subjectTeacher": "Elon"
},
{
"subjectName": "English",
"subjectTeacher": "Shakespeare"
}
]
},
{
"studentName": "test2",
"email": null,
"phnNumber": 1,
"subjects": [
{
"subjectName": "CS",
"subjectTeacher": "Elon"
},
{
"subjectName": "English",
"subjectTeacher": "Shakespeare"
}
]
}
]
Your typescript code:
this.cols = [
{ field: 'studentName', header: 'Student Name' },
{ field: 'email', header: 'Email' },
{ field: 'phnNumber', header: 'Contact No' },
{ field: '["subjects"][0]["subjectName"]', header: 'Subject Name' }
];
Your template code:
<ng-template pTemplate="body" let-student let-columns="columns">
<td *ngFor="let col of columns">
{{student[col.field]}}
</td>
</ng-template>
If you were wondering about accessing the 1st subject of student 1 in dot notation (students[0].subjects[0].subjectname), and want to replicate it in bracket notation, feel free to ask!