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"}
}
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]">