Angular - A simple way to conceal a specific row in a mat-table using Angular

I am looking to dynamically hide or show a specific column in a table by clicking on a button. The goal is to hide or delete the weight column when the "hide weight" button is clicked, and then show the weight column when the "show weight" button is clicked.

View Screenshot Here Template File:

<form class="example-form">
    <mat-form-field class="example-full-width">
      <mat-label>Elements</mat-label>
      <input matInput placeholder="search element here..." (keyup)="applyFilter($event)">
    </mat-form-field>

<button>Hide Weight</button>
 <button>Show Weight</button>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  
    <!-- Position Column -->
    <ng-container matColumnDef="position">
      <th mat-header-cell *matHeaderCellDef> No. </th>
      <td mat-cell *matCellDef="let element"> {{element.position}} </td>
    </ng-container>
  
    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>
  
    <!-- Weight Column -->
    <ng-container matColumnDef="weight">
      <th mat-header-cell *matHeaderCellDef> Weight </th>
      <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
    </ng-container>
  
   ---Other Table Columns---
    
  </table>
  <!-- </div> -->



  

TS File:

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  ---Table Data Elements---
];
@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.scss']
})
export class ProductsComponent implements OnInit {
  searchedResult:string="";
  dataSource = new MatTableDataSource(ELEMENT_DATA);
  constructor() { }

  ngOnInit(): void {
  }
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  // dataSource = ELEMENT_DATA;

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

Answer №1

If you want a straightforward solution, consider updating the buttons to change the contents of your displayedColumns variable.

Modify the buttons to trigger specific functions:

<button (click)="hideWeight()">hide weight</button>
<button (click)="showWeight()">show weight</button>

Implement the desired functionality in your TS file:

hideWeight() {
     this.displayedColumns = ['position', 'name', 'symbol'];
}

showWeight() {
     this.displayedColumns = ['position', 'name', 'weight', 'symbol'];
}

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

What is the most efficient approach to handle the next state after calling setState in react with immer?

Using Typescript, React, and Immer, I have set up a state management system to save profiles with multiple options. My goal is to ensure that the active profile has the correct option data before saving it. const { updateProfileList, getProfile } = useProf ...

How can the life cycle of a component be maintained after the constructor until the function in the constructor has finished executing?

I'm currently developing an Angular 2 application. Within this application, I have a component responsible for displaying the menu. This component contains an array of menu items that are initially set to be displayed based on permissions retrieved f ...

Transforming a JavaScript Date object to a Java LocalDateTime

In my current project, I am facing a challenge while attempting to pass UTC time from a JavaScript front end to a Java backend. My initial approach involved utilizing the Date.toISOString() method and sending the generated object to the Java backend. Howev ...

What steps do I need to take in order to develop a custom component for FormControls?

Trying to create a form with a custom component for controls, I encountered an issue. Despite including the new component in the parent form that already has a formGroup, Angular throws an error. The error I faced is: Error: formControlName must be use ...

Dealing with a situation where different functions need to be called based on a condition while using unique button names. This is

<button type="button" class="btn btn-primary ms-4" (click)="update()">Save</button> <button type="button" class="btn btn-primary ms-4" (click)="create()">Add</button> B ...

It can be time-consuming to render a large quantity of dynamic markers on Leaflet after receiving a response

Incorporating leaflet.js into my web project, I am faced with the challenge of creating a map view with dynamic markers. Upon receiving a response, I attempt to generate dynamic components based on the data and utilize change detection to monitor updates. ...

Ways to align the label at the center of an MUI Textfield

My goal is to center the label and helper text in the middle of the Textfield. I managed to achieve this by adding padding to MuiInputLabel-root, but it's not responsive on different screen sizes (the Textfield changes size and the label loses its cen ...

What is the process for importing the Scale type definition from the Scale module?

Recently, I've been utilizing the Tonal package within a Vite/Vue/Typescript project. My current task involves importing the type known as Scale from the Scale module. You can find the type definition here: export interface Scale extends ScaleType { ...

Storage in private Safari mode is not synced between tabs on mobile devices

In the private mode of mobile Safari, I have successfully stored data in the localStorage. However, when I open my web app in two separate tabs, I notice that the data stored in one tab is not accessible in the other tab. This behavior may be present in ot ...

How can the values from the scale [-60, -30, -10, 0, 3, 6, 10] be converted to a decimal range of 0-1 through

Thank you for helping me with so many of my issues. <3 I'm certain that someone has already solved this, but I'm unsure of the specific mathematical term (I've attempted reverse interpolation and others, but with no luck) so I am present ...

Although everything appears to be running smoothly in Express, my request is returning null

I am facing an issue with a router in my code. In the main index.ts file, I have the following line: app.use("/api/tshirts", tshirts) And in tshirts.ts file, I have defined the following routes: router.get("/", tshirtsController.getTShirts) router.get("/ ...

Utilizing process.env in TypeScript can be a bit tricky as dot notation is not effective for accessing its properties

When I set my scripts to: "start": "NODE_ENV=development nodemon dist/Server.js", I am encountering an issue when trying to access NODE_ENV in my code. Both dot and bracket notation return undefined: The dependencies in my project are: "@types/node": "^8. ...

What is the best way to manage data that arrives late from a service?

Within my Angular application, I have a requirement to store data in an array that is initially empty. For example: someFunction() { let array = []; console.log("step 1"); this.service.getRest(url).subscribe(result => { result.data.forEach( ...

Angular2 combined with redux fails to produce any outcomes

Currently, I am implementing redux in conjunction with angular2 and attempting to make a call to Windows Azure Search. Below is the snippet of code that I have written: types.ts export interface IAppState { languageState?: LanguageState; searchState? ...

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...

Oops! It seems like there is an issue with the Renderer2 provider in Angular v 4.1.3

Currently in the process of refactoring one of my services due to a breakage post-upgrade. I had to replace browserdomadapter(); along with several other deprecated methods. As a result of multiple deprecations starting around version 2.1 and various brea ...

ng2 inherits from component and expands upon the parent template

I have a component that inherits from a base component. Now, I would like to expand on the template of the base component within the derived component. For example: Template in base component: <div> <button>1</button> </div> ...

What measures can I take to ensure that bcrypt does not negatively impact the speed of my website

Currently, I am undertaking a project that involves Angular and Node.js. The security of different passwords is ensured by using bcrypt. However, there is an ongoing issue that has been giving me some trouble. During the registration process for new users ...

Adding a new key to a specific position in an array using Angular

After organizing my array, here is what it currently looks like: 0: Object { row: 0 } 1: Object { row: 1 } 2: Object { row: 2 } 3: Object { row: 3 } Now, I need to add a new key to position 2. The updated structure should resemble this: 0: Object { row: 0 ...

Transforming the unmanaged value state of Select into a controlled one by altering the component

I am currently working on creating an edit form to update data from a database based on its ID. Here is the code snippet I have been using: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material ...