How to call function before MatTabChange event?

Viewed 51

I have a mat-tab-group where each tab has a component with its own state, I'm handling the status of the component with a hasChanges property which tells me if the component has any changes pending to be saved.

I'm trying to show the user a dialog or alert if they decide to move to another tab while having unsaved changes, so I can prompt them to either save those changes or discard them; however, the MatTabChangeEvent only has the information of the tab I'm trying to move to, and event performs the action before running any code I write on the event handling.

Is there a way to run my code before the tab selection occurs?

Some of my code:

 onTabChanged(event: MatTabChangeEvent) {
     const i = event.index;
 
     if (this.reportPage.hasChanges) {
       const dialogRef = this.dialog.open(DialogConfirmComponent);
 
       dialogRef.afterClosed().subscribe(res => {
         if (res) {
           console.log(res);
         } else {
           this.getPage(i, this.report.pages[i].id);
         }
       });
     }
   }
1 Answers

Unfortunately, this isn't available natively. The angular team avoids the 'cancellation' of events.

Per Jeremy who works on the angular team, he mentioned an alternative is to use mat-tab-nav-bar and treat pages as routes.:

We've always avoided APIs in Angular CDK/Material that allow "cancelling" actions. The reasoning: The accessibility of "cancelling" is tricky- it's hard to communicate to screen-reader users that the expected action didn't happen and why. This would be especially true with e.g. tabs, where it would be very easy to throw off the interaction pattern if you interrupt an expected action with a dialog. There's no clear line on which actions would be cancellable and which aren't from an API consistency standpoint. It generally makes the library code more complex and harder to reason about It makes any "cancellable" interaction asynchronous This issue will stay open for conversation for now, but we don't have any plans to start adding cancellation APIs to the library. It's worth mentioning that, if you use mat-tab-nav-bar, you can treat the pages as separate routes, so that you can use route guards.

https://github.com/angular/components/issues/2013#issuecomment-623662518

Additional Reference: https://github.com/angular/components/issues/2008

Related