Ishay
Ishay

Reputation: 65

Display Array of arrays in a table

I have an Array of arrays in my data, they look like this : enter image description here

And now I want to display this array in a table, but all I get is empty page, this is my html for the table (because of code length I added only the first column code :

<table mat-table [dataSource]="dataPur" class="mat-elevation-z8" matSort>

     Name Column 
    <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Type </th>
        <td mat-cell *matCellDef="let element; let i = index"> {{element.name}} </td>
    </ng-container>


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

Component.ts :

name:string[] = [];
  iItem:number[] = [];
  iTotal:number[] = [];
  qty:number[] = [];
  dataPur:any[] = [];

  displayedColumns: string[] = ['name','iItem', 'iTotal','pretemp', 'qty'];

  ngAfterViewInit() {
    for(var i = 0; i < this.data.docDetailes.length; i++){
      this.dataPur[i] = [
    this.name[i] = this.data.docDetailes[i].name,
    this.iItem[i] = this.data.docDetailes[i].iItem,
    this.iTotal[i] = this.data.docDetailes[i].iTotal,
    this.qty[i] = this.data.docDetailes[i].qty
      ]
    }
    console.log(this.dataPur);
  }

Someone can help?

Upvotes: 1

Views: 3805

Answers (1)

Eliseo
Eliseo

Reputation: 57919

generally a datasource of a mat-table is an array of object (not an array of arrays) so, should be

for(var i = 0; i < this.data.docDetailes.length; i++){
 this.dataPur[i] = {
    name:this.data.docDetailes[i].name,
    iItem: this.data.docDetailes[i].iItem,
    iTotal: this.data.docDetailes[i].iTotal,
    qty: this.data.docDetailes[i].qty
 }
}

But really you can use an array of arrays, the only is that your td should be like

<ng-container *ngFor="let column of displayedColumns;let index=index"
     [matColumnDef]="column">
    <th mat-header-cell *matHeaderCellDef>{{column}}</th>
    <td mat-cell *matCellDef="let element; let i = index"> 
         {{element[index]}} 
    </td>
</ng-container>

see that it's not magic. "element" is the "row", so if we has an array of object we use element.[name of property] if we has an array of array simple use element[index]

Upvotes: 3

Related Questions