PrimeNg TabView with ConfirmDialog not working

Viewed 571

I'm trying to use PrimeNg TabView component along with confirmDialog unsuccessfully I am able to show this confirm dialog but it appears after user switch to target tab panel which is wrong.

<p-tabView (onChange)="handleChange($event)" [(activeIndex)]="index">...</p-tabView> 


handleChange(e) {
  this.confirmationService.confirm({
      message: 'There are unsaved changes, do you want to proceed?',
      accept:  () => {
      this.index = e.index;
      },
      reject:() =>{        }
      });
}

Do you have an idea on how to prevent or allow tab change using confirm dialog ?

Thanks

1 Answers

there is no official way to prevent change to another tab by press on that tab , but there is a work around it first we need to prevent the tab change by tab click,

1️⃣ we need to set the header by ng-template or it called a custom header

template

    <p-tabPanel >
        <ng-template pTemplate="header">
            <div (click)="handleChange($event,0)">
                Godfather I
            </div>
        </ng-template>

         .....

    </p-tabPanel>

2️⃣ we bind a click event to the new header text and by using mouse event stopPropagation method we can prevent the change ,now we can control the change by confirm result but you need to pass the current tab index, that why I add another parameter to handleChange

component

 handleChange(e:MouseEvent,tabIndex:number) {
    e.stopPropagation();
    if (this.index == tabIndex){
      return;
    }
    // console.log(tabIndex)
    this.confirmationService.confirm({
      message: "There are unsaved changes, do you want to proceed?",
      accept: () => {
        this.index = tabIndex;
      },
      reject: () => {}
    });
  }

the if block if (this.index == tabIndex){return;} use to prevent showing the confirm dialog if we click on the same active tab again

demo

Related