1

Let suppose i have elements array containing 2 items.

var elements = [{ _id: 1, name: 'Paul Walker' },
    { _id: 2, name: 'Lisa' }];

Then i have arrayelements array containing elements array

var arrayelements = [];
    arrayelements.push(elements);

i know i can bind elements array directly to datasource but how can i bind the arrayelemnts array to datasource of mat-table to show the content of elements array.

this.dataSource = new MatTableDataSource(arrayelements);

I tried this STACKBLITZ but unable to get all items in elements array

ADEEL
  • 101
  • 1
  • 7
  • 2
    On your example, you push `elements` to `arrayelements`, so finally you got only one element on your `arrayelements`. So what do you want to show on your table ? Because you will iterate over an array with only one element, which is an array. – Alexis Aug 05 '20 at 09:52
  • @LeBavarois . Got it working, thank you. unable to mark it as answer due to low reputation . sorry mate! – ADEEL Aug 05 '20 at 12:50

1 Answers1

0

@Alexis is right, you are pushing an array to an array. You could try to concat the arrays instead, for more information look for example here: Copy array items into another array

Your code would then look like this: Relevant part Component

ngOnInit() {
  var elements = [{ _id: 1, name: 'Paul Walker' },
    { _id: 2, name: 'Lisa' }];
  var arrayelements = [];
  arrayelements = arrayelements.concat(elements);
  this.dataSource = new MatTableDataSource(arrayelements);
  this.dataSource.sort = this.sort;
}

Template

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

  <!-- Position Column -->
  <ng-container matColumnDef="_id">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> No. </th>
    <td mat-cell *matCellDef="let element"> {{element._id}} </td>
  </ng-container>

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

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
LeBavarois
  • 938
  • 2
  • 11
  • 24