I'm trying to use the p-table component from primeng however I cannot display student first name and last name because its an object in headArray, what would be the recommended way around this?
My "Student" model
id: number;
name: Name;
and name model
firstName: string;
lastName: string;
HTML
<p-table [value]="students">
<ng-template pTemplate="header">
<tr>
<th *ngFor="let head of headArray">
{{head.Head}}
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-student>
<tr>
<td *ngFor="let head of headArray">
{{student[head.FieldName]}}
</td>
</tr>
</ng-template>
Typescript
public headArray = [
{ 'Head': 'Last Name', 'FieldName': 'name["lastName"]' },
{ 'Head': 'First Name', 'FieldName': 'name["firstName"]' },
{ 'Head': 'ID', 'FieldName': 'id' }
];
public getStudents(): void {
this.studentService.getStudents().subscribe(
(response: Student[]) => {
console.log(response);
this.students = response;
},
(error: HttpErrorResponse) => {
alert(error.message);
}
)
I've also tried this but no luck unfortunately
public headArray = [
{ 'Head': 'Last Name', 'FieldName': 'name.lastName' },
{ 'Head': 'First Name', 'FieldName': 'name.firstName' },
{ 'Head': 'Id', 'FieldName': 'id' }
];
the getStudents method is ran when ngOnInit is called and populates an array of students
To access nested object We could create custom pipe to transform string dot notation to object key
Examples
import { Pipe, PipeTransform } from '@angular/core';
import { Student } from './model';
@Pipe({
name: 'createPath',
})
export class CreatePathPipe implements PipeTransform {
transform(student: Student,fieldName?: string): any {
return fieldName.split('.').reduce((p, c) => (p && p[c]) || null, student);
}
}
HTML
<td *ngFor="let head of headArray">
{{ student | createPath: head.FieldName }}
</td>