javascript - 如何仅在角度表中显示匹配的列
问题描述
试图仅在表中显示匹配的列,但我不知道该怎么做。如果有人知道,请帮助找到解决方案。
app.component.ts:
columnsOnly = ['name', 'id', 'rank'];
items = [
{ name: 'jean', surname: 'kruger', id: 1, place: 'ckh', rank: null },
{ name: 'bobby2', surname: 'marais2', id: 2, place: 'ckh', rank: null },
{ name: 'jean3', surname: 'kruger3', id: 3, place: 'ckh', rank: null },
{ name: 'bobby4', surname: 'marais4', id: 4, place: 'ckh', rank: null },
{ name: 'jean5', surname: 'kruger5', id: 5, place: 'ckh', rank: null },
{ name: 'bobby6', surname: 'marais6', id: 6, place: 'ckh', rank: null }
];
app.component.html:
<table>
<thead>
<tr>
<th *ngFor="let head of items[0] | keys: index as i">
<span *ngIf="head == columnsOnly[i]">
{{head}} </span>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items">
<td *ngFor="let list of item | keys">{{item[list]}}</td>
</tr>
</tbody>
</table>
演示: https ://stackblitz.com/edit/angular-71f59e?file=app%2Fapp.component.html
解决方案
为什么不迭代 columnsOnly ?
<tr>
<th *ngFor="let column of columnsOnly">
<span>{{column}} </span>
</th>
</tr>
<tr *ngFor="let item of items">
<td *ngFor="let column of columnsOnly">{{item[column]}}</td>
</tr>
更新,嗯,一般来说,它比我们的列数组更好的是具有两个属性的对象数组,例如“标签”和“字段”。因此,假设您有一个数组列,例如
columnsOnly = [
{label:'First Name',field:'firstName'},
{label:'Sur Name',field:'surname'},
{label:'ID Type',field:'idType'},
{label:'Near Place',field:'nearPlace'}
];
我们将循环更改为
<th *ngFor="let column of columnsOnly">
<!--see that you use column.label-->
<span>{{column.label}} </span>
</th>
<tr *ngFor="let item of items">
<!--see that you use column.field-->
<td *ngFor="let column of columnsOnly">{{item[column.field]}}</td>
</tr>
更新 2另一种方法是定义所有列并制作“地图”
columns=['First Name','ID Type']
columnsOnly=this.columns
.map(x=>this.columnsAll.find(c=>c.label==x))
(columnsAll我们已经定义了“label”和“field”
推荐阅读
- python - 跳过下一个文件的标题
- list - 如何在 Flutter 中反转列表视图
- php - 如何使用 php laravel 将图像上传到服务器?
- angular - 在 Ionic 2 中使用可重用组件
- javascript - React: ".map is not a function" Issue
- doctrine-orm - Fetch EAGER not working with 2nd level relations
- eclipse - How can I run a UWP WebApp with selenium and appium?
- mysql - 当+连接时选择带大小写,MYSQL
- java - How to sort different Dates?
- firebase - Firebase 层次结构深度访问