Wednesday, 30 September 2020

Array of objects as dataSource in mat-table

I have array of objects in this structure:

data = [ 
  {
    course: 'Angular',
    students: [
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''}
    ]
  },
  {
    course: 'React',
    students: [
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''}
    ]
  },
  {
    course: 'React Native',
    students: [
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''}
    ]
  }
]

My objective is to display this student data in a mat table for each course. Expected table is to be:

__________________________________

|Name | Enrolled Date | Email      |
------------------------------------
|ANGULAR                           |
---------
|Stu1 | 20-09-2020    | stu1@gmail |
-----------------------------------
|Stu2 | 17-09-2020    | stu2@gmail |
-----------------------------------
|Stu3 | 23-09-2020    | stu3@gmail |
-----------------------------------
|REACT                             |
--------
|Stu1 | 20-01-2020    | stu1@gmail |
-----------------------------------
|Stu2 | 17-01-2020    | stu2@gmail |
-----------------------------------
|Stu3 | 25-01-2020    | stu3@gmail |
-----------------------------------
|REACT NATIVE                      |
--------
|Stu1 | 20-05-2020    | stu1@gmail |
----------------------------------
|Stu2 | 22-05-2020    | stu2@gmail |
-----------------------------------
|Stu3 | 16-05-2020    | stu3@gmail |
-----------------------------------

I need to loop the student data which is also an array. Hence, I sent data.students to mat-table dataSource by looping mat-table.

<ng-container *ngFor="let eachObj of data">
  <table mat-table [dataSource]="eachObj.students">
    <ng-container matColumnDef="name">...</ng-container>
    <ng-container matColumnDef="date">...</ng-container>
    <ng-container matColumnDef="email">...</ng-container>
  </table>
</ng-container>

Basically, the above code will pickup the first object from data array and render the table. And then pickup second object and print one more table and repeat...

I knew this is not the best approach. Can I get the better one?



from Array of objects as dataSource in mat-table

No comments:

Post a Comment