angular - 有没有办法使用更复杂的对象数据源在列而不是行上创建 Angular 动态材料表?
问题描述
我想构建一个表,其中每一列都是 API 调用的响应并包含一些元素。我用材料表尝试了不同的方法,但似乎没有任何效果。问题来自于我尝试在列而不是行上构建它(每个列上有不同数量的元素)
我也尝试过使用一个简单的表格,它可以工作,但是视图看起来不像它应该的那样。每列都包含在一个中<ng-container>
,它应该显示为一个新列,但它将它们显示在同一列上。我还尝试了一种使用 div 的方法,效果很好,但是当我向下滚动时,我无法使表格的标题变得粘滞和固定。(另外,在表格中使用 div 也不是一个好主意)这是我的表格现在的样子,是迄今为止最好的变体:
<table class="mat-table">
<ng-container *ngFor="let elem of selectedCheckValues">
<th class="mat-header-cell">{{ elem.name }}</th>
<tr id="{{element}}" *ngFor="let element of elem.items; let idx=index;" (click)="onRowClick(elem, element)">
<td class="mat-cell">{{element}}</td>
</tr>
</ng-container>
</table>
这就是我的数据的样子:
export interface SelectedCheckValues {
name: string;
items: string[];
}
其中 name 应该是表头和列中的元素。
解决方案
如果您想在 mat-table 中的列中分配一系列调用,您需要使用这些列“创建”一个 DataSource。
我做了一个简单的例子。在此我想您使用 forkJoin 获取数据,因此您可以拥有类似的东西
dataSource:any[] = [];
data=[0,1,2]
headers:string[]=[]
constructor(private dataService:DataService){}
ngOnInit(){
//we make a "typical" forkJoin where transform the "data" in an
//array of "Observables" and use forkJoin
forkJoin(this.data.map(x=>this.dataService.getData(x)))
.subscribe((res:any[])=>{
//when we has the response we "formed" the dataSource
let i=0;
let goon=true;
this.headers=res.map(x=>x.name)
while(goon)
{
const items=res.map(x=>x.items[i])
goon=items.find(x=>x!==null)
this.dataSource.push(items)
i++;
}
})
}
还有一个 .html
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container *ngFor="let header of headers;let i=index" [matColumnDef]="header">
<th mat-header-cell *matHeaderCellDef>{{header}}</th>
<td mat-cell *matCellDef="let element"> {{element[i]}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="headers"></tr>
<tr mat-row *matRowDef="let row; columns: headers;"></tr>
</table>
查看堆栈闪电战
顺便说一句,带有粘性的垫子表只有 .css,因此您可以采用使用普通表和 .css 来粘贴“标题”的方法
更新:我很难想象你是如何获取数据的,如果你使用三个对 api 的调用来获取数据
getMFTNO() //return some like [101,102,103]
getDF_RESULT() //return some like ["DL","FM","FT"]
getPERSNO() //return some like [0,000000,0000001]
并且所有 api 返回相同数量的元素,想法是使用三个调用的 forJoin 并映射到对象数组
forkJoin([this.getMFTNO(),this.getDF_RESULT(),this.getPERSNO()])
.pipe(
map(([mftno,dfResult,persno]:[any[],any[],any[]])=>{
return mftno.map((x,index)=>(
{
mftno:x,
dfResult:dfResult[index],
persno:persno[index]
}
))
}))
注意:我更新了 stackblitz 以考虑到这一点
推荐阅读
- python - Python递归:传递所有变量与仅声明全局变量并在函数中重新声明相比有什么优势吗?
- ruby - 如何创建 Google::Protobuf::Map 实例 [Ruby]
- dart - 如何在 Flutter 中的 TextFormField 中实现日期逻辑
- r - R code for pulling out fixed effect standard errors in lme4 package
- css - 使用填充弯曲五个图像
- powershell - 传递参数和运行 Powershell 脚本
- java - Web 服务客户端 - 多个 HTTP 保持活动连接到同一目标
- python - 交互式子进程的标准输出被缩短
- c# - 你好 将嵌套的 JSON 反序列化为 C# 对象
- git - 推送标签时,预推送 git 钩子会产生未知哈希