【问题标题】:How to display only few columns based on condition in mat-table using angular 6?如何使用角度 6 根据 mat-table 中的条件仅显示几列?
【发布时间】:2019-03-14 18:03:19
【问题描述】:

我有一张有几列的垫子表。对于一种情况,我需要隐藏两列。对于普通表,我们将使用简单的 ngIf 条件。但是对于这个似乎不起作用的垫子。这个我试过了,

   displayedColumns1: any[] = [
  'Ref No', 'E Type',
  { def: 'Approve', showMobile: true },
  { def: 'Transfer', showMobile: false },
  ];

    getDisplayedColumns(): string[] {
     const isMobile = this.entityRole === 'Admin';
     return this.displayedColumns1
      .filter(cd => !isMobile || cd.showMobile)
      .map(cd => cd.def);
    }

我的 HTML:

       <table mat-table [dataSource]="dataSource" class="">
        <tbody>
            <ng-container matColumnDef="Ref No">
                <th mat-header-cell *matHeaderCellDef> Ref No <br>
                </th>
                <td mat-cell *matCellDef="let element"> {{ ref }} </td>
            </ng-container>
            <ng-container matColumnDef="E Type">
                <th mat-header-cell *matHeaderCellDef> E Type <br>
                </th>
                <td mat-cell *matCellDef="let element"> {{ etype }} </td>
            </ng-container>
            <ng-container matColumnDef="Approve">
                <th mat-header-cell *matHeaderCellDef> Approve <br>
                </th>
                <td mat-cell *matCellDef="let element"> {{ Approve}} </td>
            </ng-container>
            <ng-container matColumnDef="Transfer">
                <th mat-header-cell *matHeaderCellDef> Transfer <br>
                </th>
                <td mat-cell *matCellDef="let element"> {{ Transfer }} </td>
            </ng-container>
       <tr mat-header-row *matHeaderRowDef="getDisplayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: getDisplayedColumns;"> 
       </tr>     
        </tbody>
     </table>

但它给出了 ERROR TypeError: Cannot read property 'diff' of undefined error。谁能建议我如何在 mat-table 中做到这一点?

【问题讨论】:

  • 我在您的代码中没有看到任何名为 diff 甚至 dif 的内容。如果您有关于 diff 的错误,您应该包含导致错误的代码。
  • @Igor 是的,我的代码中也没有任何称为 diff 的东西。或者您能否建议我根据某些条件显示几列?
  • 我无法在 mat table @Igor 中使用 ngIF
  • 我猜,这个错误的根源是&lt;tr mat-header-row *matHeaderRowDef="getDisplayedColumns"&gt; 处缺少括号而不是&lt;tr mat-header-row *matHeaderRowDef="getDisplayedColumns()"&gt;(以及下面的行)

标签: angular typescript angular6 mat-table


【解决方案1】:

您的问题是您的列名数组将自定义对象与字符串混合在一起,而您的过滤器没有考虑到这一点。

displayedColumns1: any[] = [
    'Ref No', 
    'E Type',
    { def: 'Approve', showMobile: true },
    { def: 'Transfer', showMobile: false }
];

getDisplayedColumns(): string[] {
  const isMobile = this.entityRole === 'Admin';
  return this.displayedColumns1
    .filter(cd => !isMobile || cd['showMobile'] !== false)
    .map(cd => typeof cd === 'string' ? cd : cd.def);
}

【讨论】:

  • 感谢您的时间和回答,我没有收到任何错误。但是那两列仍然没有隐藏..你能帮忙吗?
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 2019-01-17
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 2020-11-20
相关资源
最近更新 更多