Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Table not displaying data

What am I missing? I verified that my API is returning data back however I can't get the data to display in my table.

Verified data:

<pre>{{ myData| json }}</pre>

Html

<div *ngIf="dataSource">
  <mat-table [dataSource]='dataSource'>
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
      <mat-cell *matCellDef="let df"> {{df.name}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="path">
      <mat-header-cell *matHeaderCellDef> Path </mat-header-cell>
      <mat-cell *matCellDef="let df"> {{df.path}} </mat-cell>
    </ng-container>

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

  </mat-table>
</div>

Typescript:

export class HomeComponent implements OnInit {
  columnsToDisplay = ['name', 'path'];
  myData: IMyData[];
  dataSource = new MatTableDataSource<IMyData>(this.myData);

  constructor(private myDataService: MyDataService) { 
    console.log("IN CONSTRUCTOR");
  }

  ngOnInit(): void {
    this.myDataService.getData()
    .subscribe(x => this.myData = x,
      error => console.log("Error (GetData) :: " + error)
    ); } 
}

EDIT: I wonder if it has to do with my interface:

Interface

export interface IMyData {
  id: string;
  path: string;
  date: Date;
  location: Geolocation;
  name: string;
  gizmos: string[];
}

Example Data:

[
  {
    "id": "9653a6b5-46d2-4941-8064-128c970c60b3",
    "path": "TestPath",
    "date": "2018-04-04T08:12:27.8366667",
    "location": "{\"type\":\"Point\",\"coordinates\":[102.0,0.5]}",
    "name": "TestName",
    "gizmos": [
      "AAAA",
      "BBBB",
      "CCCC"
    ]
  }
]
like image 872
PrivateJoker Avatar asked Sep 01 '25 21:09

PrivateJoker


1 Answers

First mistake is the incorrect data binding with single quotes instead of double quotes:

Change <mat-table [dataSource]='dataSource'>

To this: <mat-table [dataSource]="dataSource">

Second mistake is incorrect data source initialization. You should create the MatTableDataSource after fetching the data from the service.

export class HomeComponent implements OnInit {
  columnsToDisplay = ['name', 'path'];
  dataSource: MatTableDataSource<IMyData>;

  constructor(private myDataService: MyDataService) {   }

  ngOnInit(): void {
    this.myDataService.getData()
     .subscribe(data => this.dataSource = new MatTableDataSource(data));
  }
}
like image 152
Tomasz Kula Avatar answered Sep 03 '25 10:09

Tomasz Kula