0

I have lwc component which has two tabs, in first tab I have first name, last name and mobile, if users enters data and without saving if he naviagtes to tab2 then alert is thrown which is fine but if user clicks on cancel in alert then it should remain in tab1 but its navigating to tab2, can any one help me out in this issue please

html:

<template>
    <lightning-tabset >
        <lightning-tab label="Tab 1" onactive={handleTab1Click}>
            <c-name-component oninputchange={handleInputChange} onsave={handleSubmit}></c-name-component>
        </lightning-tab>
        <lightning-tab label="Tab 2" onactive={handleTab2Click}>
            <c-email-component></c-email-component>
        </lightning-tab>
    </lightning-tabset>
</template>

JS:

import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {
    hasUnsavedChanges = false;

    handleInputChange() {
        this.hasUnsavedChanges = true;
    }

    handleSubmit() {
        this.hasUnsavedChanges = false;
    }

    handleTab1Click() {
        // Handle Tab 1 click if needed
    }

    handleTab2Click(event) {
        if (this.hasUnsavedChanges) {
            event.preventDefault();
            if (confirm('You have unsaved changes. Are you sure you want to navigate away?')) {
                // If user clicks OK in the confirmation dialog, navigate to Tab 2
                this.hasUnsavedChanges = false;
                event.target.click(); // Manually trigger tab switch after confirming
            }
            // If user cancels, do nothing and stay on the current tab
        }
    }
}

1 Answer 1

0

You'll have to manually set the tab:

<lightning-tabset lwc:ref="tabset">
if(confirm(confirmMessage)) {
  this.hasUnsavedChanges = false;
  this.refs.tabset.activeTabValue = 'tab2';
} else {
  this.refs.tabset.activeTabValue = 'tab1';
}

Make sure you also set the value property for each tab:

<lightning-tab label="Tab 1" value="tab1" ...
2
  • hi @sfdcfox, thanks for helping me out here, what exactly I need to manually set for below in html <lightning-tabset lwc:ref="tabset">
    – Harish
    Commented Jul 1 at 14:52
  • @Harish this.refs.tabset.activeTabValue should be set to the tab you want to be active.
    – sfdcfox
    Commented Jul 1 at 16:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .