Ho to use ngIf in a *ngFor mat table to hide columns/truncate cell content

Viewed 645

So I'm working on a mat-table ,My question is how do i hide a certain column(based on *ngIf) or truncate a cell content above 50 chars(i have a custom pipe).

if the column name is xyz hide/truncate. I'm unable to figure out a way and i am absolute newbie to angular any guidance will be very helpful. Thanks in advance

 displayedColumns: string[] = ['id','name'];

 <ng-container matColumnDef="{{column}}" *ngFor="let column of displayedColumns">
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{column}} </th>
 <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
</ng-container>

i tried doing this but it didn't work

 <ng-container matColumnDef="{{column}}" *ngFor="let column of displayedColumns">
<div *ngIf="column.length > 0 && selectedIssueTab === issueTabs[1] || selectedIssueTab === issueTabs[2]">
<th mat-header-cell *matHeaderCellDef mat-sort-header> {{column}} </th>
 <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
</div>
</ng-container>
``
1 Answers

You are applying the condition after <ng-container> is created it won't work. You can filter your ngFor loop by using a pipe like :

<ng-container matColumnDef="{{column}}" *ngFor="let column of displayedColumns | filterCells:selectedIssueTab:issueTabs[1]:issueTabs[2]">
 <th mat-header-cell *matHeaderCellDef mat-sort-header> {{column}} </th>
 <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
</ng-container>

And you can make a pipe like :

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterCells'
})
export class FilterCellsPipe implements PipeTransform {
  transform(value: any[], ...args: any[]): any {
    if (args[0] && args[1] && args[2]) {
      const selectedIssueTab = args[0];
      const issueTabs1 = args[1];
      const issueTabs2 = args[2];
      return value.filter(
        item =>
          (item.length > 0 && selectedIssueTab === issueTabs1) ||
          selectedIssueTab === issueTabs2
      );
    }
    return value;
  }
}
Related