Reputation: 1180
I am writing an angular material mat-table with a datasource but it is not rending any data
Here is my data type
interface IProfile {
jobTitle: string;
startDate: string;
endDate: string;
}
interface IAddress {
name: string;
address: string:
city: string;
state: string;
country: string;
county: string;
zipcode: string;
}
interface IEmployee {
profile: IProfile;
address: IAddress[];
}
dataSource : MatTableDataSource<IEmployee >;
dataSource.data = this.testData;
this.myData: IEmployee[]= [] ;
this.myData.push = [{ profile: this.testProfileData, address: this.testAddressData}];
this.datasource.data = this.myData;
In intellisense, I see the following content of myData
0: Object { Address: Array(21); Profile: Object }
Everything here is fine. I see the populated profile object and address array in the object after the datasource binding.
In my HTML code
<table mat-table [dataSource]="dataSource" matSort multiTemplateDataRows class="mat-elevation-z8" width="100%">
<ng-container matColumnDef="name" >
<th mat-header-cell class="table-header" *matHeaderCellDef mat-sort-header><h3>Address</h3></th>
<td mat-cell style="width: 15%;" *matCellDef="let myData">{{myData.address.name}}</td>
</ng-container>
When the UI is loading, the table is empty
I tried changing the code to the following since myData is has only 1 record with the profile object and address array
<td mat-cell style="width: 15%;" *matCellDef="let myData">{{myData.address[0].name}}</td>
But this only shows 1 value on the table. I have not gotten the UI to render all the name values in the array.
Any help is appreciated.
Update: I finally got it to populate. Is this the best approach
<ng-container matColumnDef="name" >
<th mat-header-cell class="table-header" *matHeaderCellDef mat-sort-header><h3>Name</h3></th>
<div *matCellDef="let myData">
<div *ngFor="let metric of myData.address">
<td mat-cell style="width: 15%;" >{{address.name}}</td>
</div>
</div>
</ng-container>
Upvotes: 0
Views: 1112
Reputation: 4854
this usage is not correct and you should see undefined errors in your console
<td mat-cell style="width: 15%;" *matCellDef="let myData">{{myData.address.name}}</td>
because myData.address
is an array and there is no name
property on it.
whereas,
<td mat-cell style="width: 15%;" *matCellDef="let myData">{{myData.address[0].name}}</td>
this is correct but it normally displays only the first address name because you are referencing only the first item in address
array.
what you need to do is iterate over myData.address
with *ngFor
in order to display all adresses;
<td mat-cell style="width: 15%;" *matCellDef="let myData">
<div *ngFor="let addr of myData.address">{{ addr.name }}</div>
</td>
Upvotes: 1