Is there a way to hide/show columns of lightning-datatable dynamically? Not just headers, but the whole columns?
1 Answer
The only thing you need to do is removing the desired element from the columns array, or use the original set if you want it back.
<template>
<lightning-input type="toggle"
label="Show/Hide Column"
checked={visible}
message-toggle-active="Column visible"
message-toggle-inactive="Column hidden"
onchange={handleCheckboxChange}></lightning-input>
<div style="height: 300px;">
<lightning-datatable
key-field="id"
data={data}
columns={columns}>
</lightning-datatable>
</div>
</template>
then on the controller:
import { LightningElement } from 'lwc';
import fetchDataHelper from './fetchDataHelper';
const cols = [
{ label: 'Label', fieldName: 'name' },
{ label: 'Website', fieldName: 'website', type: 'url' },
{ label: 'Phone', fieldName: 'phone', type: 'phone' },
{ label: 'Balance', fieldName: 'amount', type: 'currency' },
{ label: 'CloseAt', fieldName: 'closeAt', type: 'date' },
];
export default class BasicDatatable extends LightningElement {
visible = true;
data = [];
columns = cols;
// event to handle column display, in this example, it is just a toggle button
handleCheckboxChange(e) {
this.visible = !this.visible;
if (this.visible) {
this.columns = [...cols];
} else {
// return every column but the one you want to hide
this.columns = [...cols].filter(col => col.fieldName != 'name');
}
}
// eslint-disable-next-line @lwc/lwc/no-async-await
async connectedCallback() {
const data = await fetchDataHelper({ amountOfRecords: 100 });
this.data = data;
}
}