Concealing a column within an Angular Material table

I'm currently faced with a challenge involving an Angular Material table containing numerous columns. My goal is to selectively hide certain columns based on specific CSS media queries.

This is the code snippet I have experimented with so far:

HTML:

<ng-container matColumnDef="Speed">
  <th mat-header-cell *matHeaderCellDef>Speed</th>
  <td mat-cell *matCellDef="let row" class="mat-cell">
    <span class="speed" [ngClass]="{ 'bold': selectedSpeedNames.includes(speed.name) }" *ngFor="let speed of row.speed.$values">{{ speed.name }}</span>
  </td>
</ng-container>

CSS:

@media only screen and (max-width: 768px) and (min-width: 480px) {
  th[mat-header-cell*="Speed"],
  td[mat-cell*="Speed"] {
    display: none !important;
  }
}

I've attempted to utilize the CSS media query to conceal the "Speed" column on smaller screens (ranging from 480px to 768px), but unfortunately, it does not seem to be achieving the desired outcome. The column remains visible instead of being hidden.

What could I be missing or doing incorrectly in this scenario? Is there a more effective method to accomplish this functionality? Any assistance or recommendations provided would be highly valued. Thank you!

Answer №1

Have you ever considered why you are adding a column of data to your MatTable that doesn't actually need to be displayed? It's not necessary to resort to using CSS tricks for this. By referring to the official documentation, you will see that simply excluding the column names in the matHeaderRowDef within the tr should suffice. It's considered a good practice to avoid including unnecessary column information in your definitions or header definitions. Instead of relying on CSS queries for this purpose, you can set up your component to dynamically remove the specified columns based on the screen size.

Here is a possible implementation:

@HostListener('window:resize', ['$event'])
onResize(event) {
  if(event.target.innerWidth <= 480) {
       // Determine the index of the "speed" column in your array
       this.matHeaderRowDefValues.splice(foundIndex, 1);
  } else if(event.target.innerWidth > 480) {
       // Logic to determine where to reinsert the column
       this.matHeaderRowDefValues.splice(insertIndex, 0, "speed");
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The registration page in PHP is malfunctioning, and the reason remains a mystery to me

Having trouble with my register page submit button. Any help is appreciated. Below is the structure of my SQL table: CREATE TABLE `USERS` ( `id` int(20) NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` varchar(50) NOT NULL, `password` varchar(50) N ...

using jQuery to eliminate an HTML element based on its attribute

How can I remove an element with the attribute cursor = "pointer"? I want to achieve this using JavaScript in HTML. Specifically, I am looking to remove the following item: <g cursor="pointer"></g>. It's unclear to me why this element has ...

Unable to bring in a personalized npm package using its package title

Currently, I am loosely following a tutorial on creating an angular npm package named customlib. This package is intended for managing dependencies across my projects without the need to make them public on npm. The tutorial can be found here. However, I ...

Incorporating a PHP script into an HTML document for display

I have a PHP file that retrieves line items from a database and displays them in a table. On an HTML page, I have a form for adding items to the database that houses a restaurant menu. I want to embed the PHP script responsible for showing the line items i ...

Determine the position within the DOM of a webpage and dynamically update the navigation menu classes to reflect the changes

Help! I am trying to create a navigation menu with links that direct users to specific parts of my page. I want to use JavaScript to add a class to each navigation menu item when the scroll bar reaches the corresponding section in the HTML. I think I know ...

Do the values returned by window.screen.width and height represent CSS pixels or physical screen pixels?

After exploring the API named screen and visiting this documentation link, my initial anticipation was that I would receive information regarding actual screen size pixels. https://developer.mozilla.org/en-US/docs/Web/API/Screen/width https://i.sstatic.n ...

The perplexing actions of Map<string, string[]> = new Map() have left many scratching their heads

I encountered an issue while trying to add a value to a map in my Angular project. The map is initially set up using the following code: filters: Map<string, string[]> = new Map(); However, when I attempt to add a value to this map, it starts displa ...

Adjust the height of a div based on the font size and number of lines

I'm trying to create a function that automatically sets the height of a div by counting lines. I managed to get it partially working, but then it stopped. Can someone please help me with this? function set_height() { var div_obj=document.getEleme ...

What is the best way to update specific content with fresh URLs?

I am interested in keeping certain sections of my page static, such as the header and footer, while allowing the main content to change dynamically. Additionally, I would like the URL to update based on the new content being displayed. Although I am famil ...

Loading an entity from a service within an *ngFor loop: A step-by-step guide

Suppose I have a scenario where I need to display a list of students in Angular2. The data is fetched from a java backend using a service, and the fields are: id name age field universityId However, when displaying this data on my webpage, I want to sho ...

Ways to retrieve the text value of the first column using a button click event in JavaScript

As a beginner in HTML and JavaScript, I have a clear code provided below: HTML <tr> <td>1</td> <td>Info1</td> <td><input class="btn" value="Show" onclick="showTdSecond();" type="button"></td> & ...

Combining Sass and SCSS in webpack: A step-by-step guide

Just curious about something. I have some libraries I'm interested in using (for example, font-awesome) that use scss, but I personally prefer working with sass. How can I set up my project with webpack to accommodate this? Here's my current s ...

Steps to activate highlighting for the initial value in a quarterly datepicker

Concerning the quarterPicker feature in the Bootstrap datePicker (SO: how-to-change-bootstrap-datepicker-month-view-to-display-quarters, jsfiddle: jsFiddle): Is there a way to highlight an initial value upon startup? I have tried setting a value in win ...

Having trouble simulating a custom Axios Class in JavaScript/TypeScript

Here are the function snippets that I need to test using jest, but they require mocking axios. My attempt at doing this is shown below: // TODO - mock axios class instance for skipped Test suites describe("dateFilters()", () => { beforeEac ...

Select a random class from an array of classes in JavaScript

I have a collection of Classes: possibleEnemies: [ Slime, (currently only one available) ], I am trying to randomly pick one of them and assign it to a variable like this (all classes are derived from the Enemy class): this.enemy = new this.possibleEn ...

Understanding a compound data type in TypeScript

Hey there, I'm new to TypeScript and I'm facing a challenge in defining the type for an object that might have the following structure at runtime: { "animals" : [ { name: "kittie", color: "blue" }, { name: ...

Restrict the keys to only properties that have an array data type

Is there a way to limit the keyof operator to only accept keys of a specified type in TypeScript? interface Data { items: string[]; name: string; } // I want to restrict the keyof operator to only allow keys where the value is of type `F` type Key&l ...

Angular 16 routing not loading content

I configured the routes in Angular v16 and encountered a blank page issue with the login and register functionality. I suspect it has to do with routing, but after checking multiple times, I couldn't pinpoint the exact problem. Below are snippets of t ...

creating a stunning video background that spans 200 viewport heights

My goal is to incorporate a background video for VH1 and VH2 that remains fixed but stops at VH3. When a user opens the page, they will see #VH1 and the #videoBG as a background video. As they continue scrolling, they will reach #VH2 without the backgrou ...

What is the process for deconstructing errors from the RTK Query Mutation Hook?

Currently, I am utilizing redux toolkit query for handling my data fetching API. One issue that I have encountered is with error handling. When an error is returned from the server, it comes in as an object with nested data. However, when trying to access ...