[英]Angular 14 - Creating multiple mat-tables dynamically from JSON
我正在寻找基本上循环通过一个 JSON 看起来像这样
[
{
"name": "TESTING",
"steps": [
{
"i": "35%",
"ii": "65%",
}
]
},
{
"name": "TESTING",
"steps": [
{
"i": "35%",
"ii": "65%",
}
]
}
]
然后从这个 json 我会创建一个表,第一行是“TESTING”,步骤和它们各自的编号i, ii...。
所以像这样的事情,
TESTING
i 35%
我的第一个想法是在表上使用*ngFor
,例如<table *ngFor="let object of json">
但是我如何动态地将数据源附加到每个表?
如果这看起来毫无意义,我同意,我正在寻找更好的方法来呈现这些数据,但这是目前必须要做的。
您可以采用几种不同的方法来实现这种模式。
一个可能工作得很好的方法是利用 ngTemplateOutlet 和 ngTemplateOutletContext 指令来“搭建”模板中的 mat 表,并将数据作为上下文传递......类似于这种方法的方法可以让你开始:
@Component({
selector: 'app-table-component',
template: `
<div>
<ng-container
[ngTemplateOutlet]="tmpl"
[ngTemplateOutletContext]="ctx">
</ng-container>
<!-- Your table structure insice this template -->
<template #tmpl let-name let-location="location">
{{ name }} : {{ location }}
</template>
</div>
`
})
export class TableComponent {
ctx = {
name: 'This is a test',
location: 'Some location'
};
}
您可以想象使用此组件定义单个表,然后在循环中迭代定义app-table-components
,将ctx
数据作为输入传递。
mat-table 数据源可以是 object 的数组(问题是我们不能那么容易地排序或分页)
<mat-table *ngFor="let object of json" [dataSource]="object.steps">
</mat-table>
如果我们需要给一个 MatTableDataSource 没有问题。 我们创建 mat-tables 并在 ngAfterViewInit 中,使用 ViewChildren 获取 mat-tables 并为 MatDatasources 赋值
<!--see that we don't give dataSource-->
<mat-table *ngFor="let object of json" >
</mat-table>
@ViewChildren(MatTable) tables:QueryList<MatTable<any>>
ngAfterViewInit(){
this.tables.forEach((x:MatTable<any>,index:number)=>{
x.dataSource=new MatTableDataSource(this.json[index].items)
})
}
一个简单的堆栈闪电战
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.