首页 > 解决方案 > 如何仅在角度表中显示匹配的列

问题描述

试图仅在表中显示匹配的列,但我不知道该怎么做。如果有人知道,请帮助找到解决方案。

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

标签: javascriptangulartypescriptangular8

解决方案


为什么不迭代 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”


推荐阅读