How to prevent changing MatTab until confirmation?

Issue

I want to hold, the changing of MatTab until a confirmation is given. I have used MatDialog for confirmation. The issue is, before clicking "Yes", the the tab is already changed.

For example, From income tab, I click adjustment tab. And before switching to that tab, I need to show the popup first. But I am getting the popup after moving to adjustment tab.

th image which show the popup

component template:

 <mat-tab-group (click)="tabClick($event)">
  <mat-tab *ngFor="let tab of tabs; let index = index" [label]="tab">
    <app-spread></app-spread
  </mat-tab>
</mat-tab-group>

component ts (onClick’s method):

tabClick(clickEvent: any) {
    if (clickEvent.target.innerText != 'First') {
      this.confirm();
    }
  }
  public async confirm() {
    const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
      maxHeight: '200px',
      maxWidth: '767px',
      width: '360px',
      disableClose: true,
      data: {
        title: 'Confirmation Message',
        content:
          'There are valid statements that are not Final. Set the statements as Final?'
      }
    });
    const res = dialogRef.afterClosed().subscribe(result => {
      if (result === 1) {
        //TODO need to change the tab
      } else {
        //TODO no need to change the tab
      }
    });
  }

Solution

Sometime ago I simulate a "mat-tab" in this SO

I Imagine that you can use this with only change the function

<mat-tab-group #tabgroup style="margin-bottom:5px;" 
               animationDuration="0"   mat-align-tabs="start"
               (selectedIndexChange)="change(tabgroup,$event)">
...
</mat-tab-group>

And the function change:

  change(tab:any,index:number)
  {
    if (tab.selectedIndex!=this.indexOld){
      const dialogRef = this.dialog.open(....)
      const res = dialogRef.afterClosed().subscribe(result => {
        if (result === 1) {
           this.index=index;
        } else {
           tab.selectedIndex=this.indexOld;
        }
      });
    }
    else
    {
       this.index=index;
    }
  }

See the stackblitz -in the stackblitz I simple use the confirm dialog-

Answered By – Eliseo

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.