使Angular mat-table中的行数长于dataSource的长度

问题描述

是否有可能有一个 ma​​t-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: "Intermediate"}
      ]
   }

]

我使用 people 列表作为数据源(即长度为 2)到 mat-table,但我想生成这样的表:

姓名 生日 爱好 级别
约翰 01.01.2000 高尔夫 中级
约翰 01.01.2000 保龄球 菜鸟
约翰 01.01.2000 编程 初学者
琳达 21.12.2001 曲棍球 精英
琳达 21.12.2001 飞镖 菜鸟
琳达 21.12.2001 编程 中级

到目前为止我得到的代码是这样的(虽然提供的数据只是示例数据):

<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','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>
    

但这并没有产生想要的结果,即爱好列表中的每个元素都有新的表格行。

有没有人有办法解决这个问题?也许不需要在将所有爱好作为新列表项保存的组件中创建一个新列表(即,John 的姓名和生日有 3 个重复,Linda 的姓名和生日有 3 个重复)。

感谢我能得到的所有帮助

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)