Is there a way to execute a function prior to the MatTabChange event?

Within my mat-tab-group, each tab contains its own component with a unique state. I utilize a hasChanges property to track if there are any pending changes in the component that need to be saved.

I am currently facing the challenge of notifying the user with a dialog or alert when they attempt to navigate to another tab without saving their unsaved changes. The issue lies in the fact that the MatTabChangeEvent only provides information about the tab being navigated to, and executes the action before allowing me to run my custom code for handling the event.

Is there a method for executing my code prior to the tab change taking place?

Snippet from my current implementation:

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

Answer №1

Regrettably, this feature is not available by default. The Angular team intentionally avoids implementing 'cancellation' of events.

According to Jeremy from the Angular team, an alternative approach suggested is utilizing mat-tab-nav-bar and treating pages as routes:

The Angular CDK/Material has always steered clear of providing APIs that support "cancelling" actions. The rationale behind this decision includes: Difficulty in conveying to screen-reader users that the expected action was not executed and why, especially challenging with elements like tabs which may disrupt user interaction if interrupted by a dialog. Lack of clarity on determining which actions should be cancellable for API consistency. Increase in code complexity and difficulty in understanding library code. Introduction of asynchronous behavior in any "cancellable" interactions. While this topic will remain open for discussion, there are no current plans to incorporate cancellation APIs into the library. It's worth noting that using mat-tab-nav-bar allows you to treat pages as distinct routes and utilize route guards.

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

For further information, refer to: https://github.com/angular/components/issues/2009

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function with which you are trying to use 'new' does not have a call or construct signature

How can I prevent the error from appearing in my console.log? An error message - 'Cannot use 'new' with an expression whose type lacks a call or construct signature.' - keeps popping up. var audioContext = new window.AudioContext() ...

A guide on incorporating a button into a column within ng2table in Angular 2

I am currently using ng2table and I have all the columns being appended from ts. However, I would like to add a button to each of these columns. Can someone please assist me with how to achieve this? Thank you. columns: Array<any> = [ {tit ...

Angular threw an error saying: "Template parse errors: is not a recognized element"

I am attempting to utilize babel standalone within a react application to transpile Angular TypeScript. The transpiling process seems to be successful, however, I encounter an error when trying to import a component and use its selector within the template ...

Challenges arise when working with Angular using ngrx and typescript, particularly when dealing

I'm encountering an issue while working with ngrx. I keep receiving an error when attempting to implement a simple effect. The specific error message mentions that the Argument of type 'MonoTypeOperatorFunction<LoadContainerAction>' is ...

Passing an identifier between components in Angular 6

My current situation: After logging in using the Login Component, I receive a response from the API like below: { code: 200, id: 4, msg: "success", user: "Sourav" } My goal is to pass this id to the Candidate Component, CV Details Component, and ...

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

Determine the types of values for an object through the use of Generics

After spending a while pondering over this issue, I have yet to discover an elegant solution. My dilemma begins with an Enum: export enum Enum { A, B, C, } Next, there is an object that utilizes the Enum. While the structure is somewhat predi ...

Troubleshooting problem with iPhone X responsiveness

Struggling with responsive issues on iPhone X. Issue is only appearing on actual device. Any tips for fixing this? I'm facing an issue where the website looks good and responsive on all devices in Chrome's responsive view. But when I access it th ...

Guide on displaying and handling server-side validation errors within an angular form

I recently started working with Angular and encountered a problem I can't seem to solve. In my form, I need to display server validation errors from a Laravel REST API response. Although I can see the error message in the console, I'm unsure how ...

Having trouble with removing a language from the router in Next.js when using ni18n?

I've been working on a website using ni18n with Next.js, but I'm having trouble removing the language part from the URL even after trying to force remove it. What I'm aiming for is a URL like this: "http://localhost:3000" Howeve ...

To display a specific router link and its child routes, make use of the *ngIf directive

Issue: How can we display [content] in all child routes of a parent route such as <div *ngIf="router.url === '/parent/child'">[content]</div>, ensuring that content is shown in ./parent/child1, ./parent/child2, and so on? P ...

The issue of NestJS dependency injection not working within the MongooseModule.forFeatureAsync function call has been encountered

I'm having an issue setting up a pre-save hook on my User model. Here's the code snippet from my users.module.ts: @Module({ controllers: [ UsersController, ], exports: [ UsersService, ], providers: [ UsersService, ], imp ...

What is the essential Angular 2 script that must be included for a simple Angular 2 application to function properly?

I'm currently working through the latest Tuts+ tutorial on Angular 2 In the tutorial, the author references adding this script: <script src="node_modules/angular2/bundles/angular2.sfx.dev.js"></script> However, in the most recent beta re ...

A tutorial on how to customize the hover effect for TableHead Column Identifiers in MaterialUI by adjusting

I'm struggling to customize the appearance of child th elements using the TableHead component from MaterialUI. While I've been successful in modifying various properties, I'm facing difficulty in changing the hover color. Below is the snipp ...

Using Rust WebAssembly in Next.js

Seeking assistance with integrating a rust-generated wasm module into my NextJS project. This is how I am attempting to import the wasm: import init, { tokenize } from "@/wasm/lazyjson"; const Test = dynamic({ loader: async () => { ...

React: Switching PopUp causes the entire component to be re-rendered

Currently, I am in the process of familiarizing myself with React, so I appreciate your patience. I am developing a component using MaterialUI which consists of a grid and a PopOver. A basic mockup of this component is as follows: export const Overview ...

Developing a custom pipe in Angular4

Can anyone explain why the code snippet below has (limit) in parentheses? import { Pipe, PipeTransform } from '@angular/core' @Pipe ({ name: 'summary' }) export class SummaryPipe implements PipeTransofm { transform(value: string, l ...

A guide on implementing TypeScript with React Native's platform-specific extensions

The issue at hand: In my react native project, I am using a custom hook that has platform-specific code. I need to import this hook based on the platform in use. When I import it as import useWifi from 'hooks/use-wifi.android';, everything works ...

Styling child elements in Angular using css from its parent element

I have a question: Regarding the structure below <component-parent> <first-child> <second-child> <third-child></third-child> </second-child> </first-child> </component-parent> Now I want t ...

Incorporating data from an api call to establish the starting state of a react component

I have been delving into the world of React and TypeScript while working on a fun project - a word guessing game inspired by Hangman. In this game, players have 5 chances to guess the correct word, which is retrieved from an API call. I populate an array w ...