【发布时间】:2021-07-11 14:55:36
【问题描述】:
是否有可能有一个 mat-table 输出的数据行数超过所提供数据源的长度?以此类数据为例:
people: [
{
name: "John",
birthday: "01.01.2000",
hobbies: [
{type: "Golf", level: "Intermediate"},
{type: "Bowling", level: "Noob" },
{type: "Programming", level: "Beginner"}
]
},
{
name: "Linda",
birthday: "21.12.2001",
hobbies: [
{type: "Hockey", level: "Elite"},
{type: "Dart", level: "Noob" },
{type: "Programming", level: "Intermediate"}
]
}
]
我使用 people 列表作为 mat-table 的数据源(即长度 2),但我想生成这样的表格:
| Name | Birthday | Hobby | Level |
|---|---|---|---|
| John | 01.01.2000 | Golf | Intermediate |
| John | 01.01.2000 | Bowling | Noob |
| John | 01.01.2000 | Programming | Beginner |
| Linda | 21.12.2001 | Hockey | Elite |
| Linda | 21.12.2001 | Dart | Noob |
| Linda | 21.12.2001 | Programming | Intermediate |
目前得到的代码是这样的(虽然提供的数据只是示例数据):
<mat-table [dataSource]="dataSource">
<ng-container mathColumnDef="name">
<mat-header-cell *matHeaderCell> Name </mat-header-cell>
<mat-cell *matCellDef="let col">{{ col.name }}</mat-cell>
</ng-container>
<ng-container mathColumnDef="birthday">
<mat-header-cell *matHeaderCell> Birthday </mat-header-cell>
<mat-cell *matCellDef="let col">{{ col.birthday }}</mat-cell>
</ng-container>
// the next two columns is where the problem lies.
// I only getting the first hobby in list to have a valid code.
<ng-container mathColumnDef="hobby">
<mat-header-cell *matHeaderCell> Hobby </mat-header-cell>
<mat-cell *matCellDef="let col">{{ col.hobbies[0].type }}</mat-cell>
</ng-container>
<ng-container mathColumnDef="level">
<mat-header-cell *matHeaderCell> Level </mat-header-cell>
<mat-cell *matCellDef="let col">{{ col.hobbies[0].level }}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="['name', 'birthday', 'hobby', 'level']">
<mat-row *matRowDef="let row; columns: ['name', 'birthday', 'hobby', 'level']"></mat-row>
</mat-table>
其中 dataSource 是人员列表。此外,爱好列表可以有不同的长度。
我试过了:
-
在 mat-cell 上添加 *ngFor 指令,但不允许在同一元素上使用两个结构指令
-
我还在 mat-cell 元素内的 ng-container 上尝试了 *ngFor 指令,如下所示:
<mat-cell *matCellDef="let col"> <div> <ng-container *ngFor="let item of col.hobbies"> {{ item.type }} </ng-container> </div> </mat-cell>
但这并没有创建想要的结果,即爱好列表中每个元素的新表行。
有没有人可以解决这个问题?也许不需要在包含所有爱好的组件中创建一个新列表作为新列表项(即约翰的姓名和生日有 3 个重复项,琳达的姓名和生日有 3 个重复项)。
感谢我能得到的所有帮助
【问题讨论】:
-
也许这可能会有所帮助stackoverflow.com/questions/54293513/…
标签: javascript angular angular-material angular2-directives mat-table