Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 material table hide column

I have the following angular2 material table

<mat-table #table [dataSource]="dataSource" >

        <!--- Note that these columns can be defined in any order.
              The actual rendered columns are set as a property on the row definition" -->

        <!-- Position Column -->
        <ng-container matColumnDef="selected">
            <mat-header-cell *matHeaderCellDef>
                <mat-checkbox [(ngModel)]="selectAll"></mat-checkbox>
            </mat-header-cell>
            <mat-cell *matCellDef="let element">
                <mat-checkbox [(ngModel)]="element.selected" [checked]="selectAll"></mat-checkbox>
            </mat-cell>
        </ng-container>

        <ng-container matColumnDef="id">
            <mat-header-cell *matHeaderCellDef> Id</mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.id}}</mat-cell>
        </ng-container>

        <ng-container matColumnDef="requested_status">
            <mat-header-cell *matHeaderCellDef> Status</mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.requested_status}}</mat-cell>
        </ng-container>
        ......

I need to hide a column in the table by some boolean condition. Is it possible without changing columns map in my component?

displayedColumns = ['selected', 'id', ...];

I tried to use *ngIf but it doesn't work. How to do that?

like image 998
avalon Avatar asked Nov 02 '17 14:11

avalon


3 Answers

no need of any directives.

just use

[hidden] it will work ex:[hidden]="show" in html and set show to boolean in ts file.

my html code:

<ng-container matColumnDef="department" >
  <mat-header-cell [hidden]="show" *matHeaderCellDef> 
    Department 
  </mat-header-cell>
  <mat-cell [hidden]="show" *matCellDef="let element">
    {{element.department}}
  </mat-cell>
</ng-container>
like image 150
Goutham S Avatar answered Oct 31 '22 19:10

Goutham S


The angular way to do this is to update the columns passed to your row template:

HTML:

<mat-row *matRowDef="let row; columns: getDisplayedColumns();"></mat-row>

TS:

const columnDefinitions = [
  { def: 'col1', showMobile: true },
  { def: 'col2', showMobile: false },
];

getDisplayedColumns(): string[] {
  const isMobile = this.currentDisplay === 'mobile';
  return this.columnDefinitions
    .filter(cd => !isMobile || cd.showMobile)
    .map(cd => cd.def);
}
like image 21
Lucas Avatar answered Oct 31 '22 19:10

Lucas


To the column you want to hide, add this:

[style.display]="'none'"

You should add to both the mat-heather-cell and the mat-cell.

like image 14
Rod Astrada Avatar answered Oct 31 '22 18:10

Rod Astrada