Is there a way to hide/show columns dynamically (not just headers,the whole columns) of a datatable in lightning web components? Can you provide an example please?

1 Answer 1


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.

    <lightning-input type="toggle" 
        label="Show/Hide Column" 
        message-toggle-active="Column visible"
        message-toggle-inactive="Column hidden"
    <div style="height: 300px;">

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.