Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 941
sasi Avatar asked Sep 02 '25 05:09

sasi


2 Answers

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);
}
like image 119
Igor Avatar answered Sep 04 '25 23:09

Igor


displayedColumns: any[]
if (this.entityRole == 'Admin')
   { this.displayedColumns = ['name', 'dob', 'grade', 'address'] }
else
   { this.displayedColumns = ['name', 'dob', 'grade']  }
like image 45
Molly Avatar answered Sep 05 '25 01:09

Molly