How to hide and show tab in Lightning Tab Set in Salesforce Lightning Web Component(LWC)?

How to hide and show tab in Lightning Tab Set in Salesforce Lightning Web Component(LWC)?

Sample Code:

HTML:

<template>
    <lightning-card>
        <lightning-button variant="brand" label="Show Tab 1" onclick={handleClick}></lightning-button>
        <lightning-button variant="brand" label="Show Tab 2" onclick={handleClick}></lightning-button>
        <lightning-button variant="brand" label="Hide Tab 1" onclick={handleClick}></lightning-button>
        <lightning-button variant="brand" label="Hide Tab 2" onclick={handleClick}></lightning-button>
        <lightning-tabset variant="scoped">
            <template if:true={tabOneBool}>
                <lightning-tab label="Item One"> Content for tab 1 </lightning-tab>
            </template>
            <template if:true={tabTwoBool}>
                <lightning-tab label="Item Two"> Content for tab 2 </lightning-tab>
            </template>
        </lightning-tabset>
    </lightning-card>
</template>

JavaScript:

import { LightningElement } from 'lwc';

export default class TabSet extends LightningElement {

    tabOneBool;
    tabTwoBool;

    handleClick( event ) {

        let buttonClicked = event.target.label;

        switch( buttonClicked ) {

            case 'Show Tab 1':
                this.tabOneBool = true;
                break;

            case 'Show Tab 2':
                this.tabTwoBool = true;
                break;

            case 'Hide Tab 1':
                this.tabOneBool = false;
                break;

            case 'Hide Tab 2':
                this.tabTwoBool = false;
                break;
            
        }

    }

}

js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply