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
}
}
}