Home > other >  Method to structure my json data for monthly attendance?
Method to structure my json data for monthly attendance?

Time:08-22

I have a material table that looks like this: Click here to see the image

and i have a json server set up with data in the format:

{
  "posts": [
    {
      "empid": 12345,
      "name": "Dharini Iyer",
      "dates":[
      {"1": "Absent",
      "2": "Present",
      "3": "Present",
      "4": "Absent",
      "5": "Present"}]
     }
  ]
}

In order to fill the material table daywise, I needed to know how to retrieve the daywise attendance as an array from the json file and how to store it there.

CodePudding user response:

To achieve your goal [Stackblitz solution]

.ts file

create four arrays in the .ts file, just like

  days: string[] = Array.from({ length: 31 }, (_, i) => String(i   1)); // holds dates 1 to 31
  displayedColumns: string[] = ['name', 'empid']; // holds remaining details
  columnsToDisplay: string[] = [...['name', 'empid'], ...this.days].slice(); // holds which columns needs to be displayed in table

  data: any[] = [] //holds your actual data

that's it from the .ts file.

HTML file

just create a basic mat-table and provide data to table dataSource. just loop two arrays that we created in the .ts file. check below code t see which arrays need to be looped.

<table mat-table [dataSource]="data" >
  <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
    <th mat-header-cell *matHeaderCellDef>{{column}}</th>
    <td mat-cell *matCellDef="let element">{{element[column]}}</td>
  </ng-container>
  <ng-container [matColumnDef]="column" *ngFor="let column of days">
    <th mat-header-cell *matHeaderCellDef>{{column}}</th>
    <td mat-cell *matCellDef="let element">
      {{element?.dates[0][column]?.substring(0, 1)}}
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>

  • Related