Skip to content Skip to sidebar Skip to footer

Iterate Through Datasource In Mat-table Angular

I have problem with iterations through dataSource, where I have data for mat-table

Solution 1:

Another way how to iterate through dataSource elements:

dataElement:DataElement[]= [
    {position:1, name:'Hy', weight:1.0079, height:3.33},
    {position:2, name:'He', weight:4.0026, height:4.21},
    {position:3, name:'Li', weight:6.941, height:10.1},
    {position:4, name:'Be', weight:9.0122, height:11},
    {position:5, name:'Bo', weight:10.811, height:85},
    {position:6, name:'Ca', weight:12.0107, height:8.5},
    {position:7, name:'Ni', weight:14.0067, height:85.1},
    {position:8, name:'Ox', weight:15.9994, height:0.85},
    {position:9, name:'Fl', weight:18.9984, height:123},
    {position:10, name:'Ne', weight:2110.1797, height:8}
  ];columns= [
    {columnDef:'position', header:'No.', cell:(element:DataElement)=>`${element.position}`},
    {columnDef:'name', header:'Name', cell:(element:DataElement)=>`${element.name}`},
    {columnDef:'weight', header:'Weight', cell:(element:DataElement)=>`${element.weight}`},
    {columnDef:'height', header:'Height', cell:(element:DataElement)=>`${element.height}`},
    {columnDef:'result', header:'Result', cell:(element:DataElement)=>`${element.result}`}
  ];displayedColumns=this.columns.map(result=>result.columnDef);dataSource=this.dataElement;

and finally the html:

<mat-table #table [dataSource]="dataSource"><ng-container *ngFor="let column of columns" [cdkColumnDef]="column.columnDef"><mat-header-cell *cdkHeaderCellDef>{{ column.header }}</mat-header-cell><mat-cell *cdkCellDef="let row">{{ column.cell(row) }}</mat-cell></ng-container><mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row><mat-row *matRowDef="let row; columns: displayedColumns"></mat-row></mat-table>

REPO: https://stackblitz.com/edit/angular-mat-table-create-dynamically

Solution 2:

Try using index with ngFor to track your iterations. I hope its helpful.

<div *ngFor="let element of arrayMain, let myIndex=index"id="{{element}}"class="my_item"><div><spanclass="skuska"><spanclass="mat-subheading-2">{{element}}</span></span></div><mat-table #table [dataSource]="dataSource[myIndex]"matSort><ng-containermatColumnDef="{{column.id}}" *ngFor="let column of columnNames"><mat-header-cell *matHeaderCellDefmat-sort-header>
                {{column.value}} 
            </mat-header-cell><!-- your same code --></ng-container></mat-table></div>

Post a Comment for "Iterate Through Datasource In Mat-table Angular"