我正在用数据源编写一个有角度的材质表,但是它没有存放任何数据
这是我的数据类型
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;
在智能感知中,我看到了myData的以下内容
0:对象{地址:Array(21);配置文件:对象}
这里的一切都很好。在数据源绑定之后,我在对象中看到了填充的配置文件对象和地址数组。
在我的HTML代码中
<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>
在加载UI时,表为空
我尝试将代码更改为以下代码,因为myData只有1条记录包含配置文件对象和地址数组
<td mat-cell style="width: 15%;" *matCellDef="let myData">{{myData.address[0].name}}</td>
但这仅在表上显示1个值。我还没有UI来呈现数组中的所有名称值。
感谢您的帮助。
更新:我终于把它填充了。这是最好的方法
<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>
答案 0 :(得分:1)
此用法不正确,您应该在控制台中看到未定义的错误
<td mat-cell style="width: 15%;" *matCellDef="let myData">{{myData.address.name}}</td>
因为myData.address
是一个数组,并且没有name
属性。
而
<td mat-cell style="width: 15%;" *matCellDef="let myData">{{myData.address[0].name}}</td>
这是正确的,但是通常只显示第一个地址名称,因为您仅引用address
数组中的第一个项目。
您需要做的是用myData.address
遍历*ngFor
以显示所有地址;
<td mat-cell style="width: 15%;" *matCellDef="let myData">
<div *ngFor="let addr of myData.address">{{ addr.name }}</div>
</td>