【问题标题】:How to show matched column only in table in angular如何仅在角度表中显示匹配的列
【发布时间】:2021-07-31 18:21:10
【问题描述】:

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

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

【问题讨论】:

    标签: javascript angular typescript angular8


    【解决方案1】:

    你为什么不只遍历 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我们已经定义了“标签”和“字段”

    【讨论】:

    • 有时会得到空白值 -{{item[column]}}
    • 如果列的值是对象属性的名称并且具有值,则应该可以工作。在你的例如“rank”为空,所以不显示任何值-。注意,Angular 是区分大小写的——它的“Rank”与“rank”不同——
    • 这种情况下怎么匹配呢?假设数组属性名称为驼峰式? stackblitz.com/edit/angular-ksymng?file=app%2Fapp.component.ts
    • 我更新了答案。这个想法是,columns 是一个具有两个属性的对象数组:label - 您在表标题中看到的标签,field 是列的真实名称。好吧,您也可以拥有一个字符串数组并想象一种解析数组以获取标题或列名称的方法,但实际上我认为使用对象数组的方法更“健壮”跨度>
    猜你喜欢
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2023-03-22
    相关资源
    最近更新 更多