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?
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>
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With