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

Retrieving the <html> tag within an Angular component

In an Angular component, the <body> and <head> tags can be accessed by injecting DOCUMENT as shown below: import { DOCUMENT } from '@angular/common'; import { Inject } from '@angular/core'; export class TestComponent { c ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

Tips on streamlining two similar TypeScript interfaces with distinct key names

Presented here are two different formats for the same interface: a JSON format with keys separated by low dash, and a JavaScript camelCase format: JSON format: interface MyJsonInterface { key_one: string; key_two: number; } interface MyInterface { ...

Guide on integrating a plain Service/Provider into nest.js

I recently created a basic TypeScript class in nest.js called JwtTokenService.js. // JwtTokenService.js import { Injectable, Optional } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { JwtPayload } from ' ...

Having issues with autocompletion in the input element of Angular 7 Material Design

My Angular 7 application includes a Material Design form with input text fields, and I have not implemented any autocomplete feature within the code. Despite deleting all navigation data from my Chrome browser, I am still experiencing autocomplete suggesti ...

Unit testing in Angular - creating mock services with observables

I'm currently facing an issue with my unit tests for a component that subscribes to an Observable from the service DataService in the ngOnInit() lifecycle hook. Despite my efforts, I keep encountering the error message TypeError: Cannot read propertie ...

Leveraging the Cache-Control header in react-query for optimal data caching

Is it possible for the react-query library to consider the Cache-Control header sent by the server? I am interested in dynamically setting the staleTime based on server instructions regarding cache duration. While reviewing the documentation, I didn&apos ...

Exploring the integration of traditional service methodologies into modern Angular applications

I am tasked with converting various types of services like SOAP-based services, WCF XML services, and web services that are currently running in a Silverlight app. For this conversion, we plan to use Angular as the front end while keeping the server side u ...

Child component experiencing issues with Materialize Pagination and Sorting functionalities not functioning

New to materialize pagination and currently working on the hierarchy below: app modules > list > list.component app.component Implemented a sample code example in app.component which worked perfectly. However, encountered issues when trying to imp ...

What is the best approach to implement a recursive intersection while keeping refactoring in consideration?

I'm currently in the process of refactoring this code snippet to allow for the reuse of the same middleware logic on multiple pages in a type-safe manner. However, I am encountering difficulties when trying to write a typesafe recursive type that can ...

What is the best way to showcase nested array information within a form array in Angular2?

I recently incorporated FormGroup into my Angular 2 project to facilitate form rendering. For handling nested array data, I opted for formArray. form.component.html <div class="col-md-12" formArrayName="social_profiles"> <div *ngFor="let socia ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

After importing this variable into index.ts, how is it possible for it to possess a function named `listen`?

Running a Github repository that I stumbled upon. Regarding the line import server from './server' - how does this API recognize that the server object has a method called listen? When examining the server.ts file in the same directory, there is ...

Dependency injection in Angular 2 service not functioning as expected

I am facing an issue while trying to retrieve static data from UserService in Angular 2. Although everything seems correct based on the documentation, it is not functioning as expected. Below is my UserComponent.ts import {Component ,OnInit } from ' ...

Plugin for listing contacts using Nativescript

I am currently developing a contact list application using NativeScript with Angular. I have integrated the nativescript-contacts plugin into my project and everything is working smoothly on the iOS emulator on macOS High Sierra. Following the documentatio ...

steps for retrieving final outcome from forkJoin

I am currently working with an array of userIds, such as: ['jd', 'abc']. My goal is to loop through these userIds and retrieve full names using an API. Ultimately, I aim to transform the initial array into [ {userId: 'jd', nam ...

Is it possible to incorporate a nested form in Angular reactive forms without utilizing an array?

this.parentForm = this._fb.group({ testControl1: [], testControl2: [], testChildForm1: this._fb.group({ testChildControl1: [], testChildControl2: [] }) )}; The parent form in the code above has two form controls and on ...

Unable to access setRowData() in AgGrid/Angular 2 leads to rendering of the grid without displaying any rowData

Resolved I think my solution is temporarily fixed and it reveals that I may have set up my mongoose model incorrectly. The answer provided did assist me in solving my issue, but ultimately the reason for the empty data rows was due to incorrect identifier ...

Is there a surefire method to ensure that ChromeDriver in Protractor consistently uses the stable version?

Every time Chrome releases an update, I encounter a recurring issue. Allow me to paint the picture: All browsers are at version 83 of Chrome Chrome announces that version 84 is on its way, but it has not been released yet. A new ChromeDriver 84 is rolled ...

Leverage the capabilities of one service within another service

I have been working on enhancing the functionality of Http so that when a user encounters a 403 error, their user information is removed and they are redirected to the login page. I have shared an example of AuthHttp below for reference. @Injectable() ...