Search code examples
angulartypescriptangular6mat-table

How to display only few columns based on condition in mat-table using angular 6?


I have a mat table which is having few columns. Here for one condition I need to hide two columns. For normal table, we would use simple ngIf condition. But for this mat-table that seems to be not working. I have tried this,

   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);
    }

My 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>

But it gives ERROR TypeError: Cannot read property 'diff' of undefined error. Can anybody please suggest me how can I do that in mat-table ?


Solution

  • Your issue is that your column name array is mixing a custom object with strings and your filter is not taking that into consideration.

    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);
    }