3

I am new to Angular and Angular Material ,

Without Angular Materail it is working fine

<table>
  <tr>
    <th>City</th>  
    <th>State</th>
  </tr>

  <tr>
      <td>{{ varEmp?.address.city}}</td>
      <td>{{ varEmp?.address.state}}</td>

    </tr>

</table>

With Angular Material it is not Working

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


  <!-- Position Column -->
  <ng-container matColumnDef="city">
    <th mat-header-cell *matHeaderCellDef> City</th>
    <td mat-cell *matCellDef="let element"> {{element?.address.city}} </td>
  </ng-container>

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

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

In component I declared variable

displayedColumns: string[] = ['city','state'];

briefy described component code to reduce complexity

Json Object

{"address":
   {"city": "Karwar", "state": "Karnataka"}
}
Pavan Kumar R
  • 31
  • 1
  • 1
  • 3

4 Answers4

5

I stumbled upon this issue as I had a static data source of json format and I needed to dump it in a mat-table.

The most common reason for this behavior is poor format of json data. The json data expected by mat-table should be in the format [{...}, {...}, {...}]. If you cannot change the format of the json data, simply convert the data to Array like this

var dataArr = new Array(jsonData));

and it would work.

Note - Converting it to array would add an extra layer of square brackets to the data. You might need to change the [dataSource] property in mat-table to dataArr[0].

<table mat-table [dataSource]="dataArr[0]">

M M
  • 655
  • 1
  • 7
  • 16
2

Define the datasource of table as ;

this.dataSource = new MatTableDataSource<Address>(this.addressList);
Selman Gun
  • 141
  • 1
  • 7
0

You need to convert your data to an array.

[dataSource] for angular material mat-table, requires that an array of data is passed to it. Ensure that you have a well formatted array of your data before assigning to your data source

valentine
  • 457
  • 8
  • 17
0

You could try edit the td tag and do not use ? after the element. For example:

<td mat-cell *matCellDef="let element"> {{element.address.city}} </td>