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();
}
}