1
votes

The mat table (angular) datasource has a data(array with one row) but just displays the header and the table is empty.

The problem is that the console in ngOnInit shows data, but my table is empty and only displays a header. What's wrong with my simple code?

Code in my component html file:

<div class="mat-elevation-z8 show-feature">
  <mat-table #table [dataSource]="samples">
    <!-- from Column -->
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
      <mat-cell *matCellDef = "let row">
        {{row.name}}
      </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef='displayedColumns'>
      <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-header-row>
  </mat-table>
</div>

Code in my component ts file:

export class SpliceConnectionsAttributeControl implements 
        AfterContentInit, OnInit, OnDestroy {


  samples: Samples[];
  displayedColumns = ['name'];

  constructor() { }

  ngOnInit() {
    this.samples = [{name: 'test1'}];
    console.log(this.samples);
  }

  ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }

  ngAfterContentInit() { }
}

Model:

export class Samples {
  name: string ;
}
2

2 Answers

0
votes

Your template syntax is wrong, you should use table, th, tr and td tags with angular material directives:

<table mat-table #table [dataSource]="samples">
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
     <td mat-cell *matCellDef="let row">
       {{row.name}}
     </td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef='displayedColumns'></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

DEMO: STACKBLITZ