Hiding Angular Material Data Table Columns

Photo by Dawid Zawiła on Unsplash

Updated Version

There’s an updated version of this article here:

Scenario

We have a material data table with the colums id and Decription . We want to have two mat-checkbox fields, one for id and one for description that when clicked hide the corresponding column in the data table.

Approach

We’ll use a columnsDefinitions object to store which column definitions are hidden:

columnDefinitions = [
{ def: 'id', hide: this.cb1.value},
{ def: 'description', hide: this.cb2.value}
]

The RxJS merge operator is used to observe the mat-checkbox fields and update the columnDefinitions :

Finally we’ll filter the columnDefinitions to get the columns we want to display:

getDisplayedColumns():string[] {
return this.columnDefinitions.filter(cd=>!cd.hide).map(cd=>cd.def);
}

And we’ll use getDisplayedColumns in our template like this:

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

Demo

Simpler Demo

This demo is shorter. It uses a displayedColumns$:Observable<string[]> to display the columns. This should be better from a performance point of view, since the getDisplayedColumns() function will not be called on all state changes.

Related Concepts

Brought to You By

Founder of Firefly Semantics Corporation

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Process(ing): Generative Irregular Grid

Yes, WordPress is Horizontally Scalable

Legendary Giveaway! Winning a Steam Deck is as Easy as 1, 2, 3!

How to Get “Unstuck” While Coding

Velocity in Software Engineering

Crafting a Useful & Extensible Toolchain

Download [PDF] The Filmmaker’s Eye: Learning (and Breaking) the Rules of Cinematic Composition Full…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation

More from Medium

Angular 13: Server Side Form Validations in Ant Design

Angular reactive forms: Generic directive to focus on invalid input

Coffee mug with the text: “Go get them”

An in-depth look at Angular’s ng template

Unit Testing in Angular(Part 1)