Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally prevent user from navigating to other tab in mat-tab-group

I have an angular component which uses an angular material tab group.

<mat-tab-group>
  <mat-tab label="First"> <app-comp1></app-comp1> </mat-tab>
  <mat-tab label="Second"> <app-comp2></app-comp2> </mat-tab>
  <mat-tab label="Third"> <app-comp3></app-comp3> </mat-tab>
</mat-tab-group>

In a certain tab, user can do some changes and save. If user did some changes and tries to navigate to another tab without saving, I want to ask the user for confirmation to discard changes before navigating to the other tab.

Is there any way to do this?

like image 957
Lahiru Chandima Avatar asked Nov 30 '22 08:11

Lahiru Chandima


2 Answers

The accepted answer has stopped working for me in the latest vue version.

Another option is to set the other tabs to disabled when the active tab is in a state that is incomplete.

<mat-tab-group>
  <mat-tab label="Form">Form Here</mat-tab>
  <mat-tab label="Result" >Result Here</mat-tab>
</mat-tab-group>
like image 36
GeekyMonkey Avatar answered Dec 05 '22 19:12

GeekyMonkey


If there is no solution today then i can offer you some trick based on monkey patching:

template.html

<mat-tab-group #tabs>
  ...
</mat-tab-group> 

component.ts

import { MatTabGroup, MatTabHeader, MatTab } from '@angular/material';
...
@Component({...})
export class AppComponent implement OnInit {
  @ViewChild('tabs') tabs: MatTabGroup;

  ngOnInit() {
    this.tabs._handleClick = this.interceptTabChange.bind(this);
  }

  interceptTabChange(tab: MatTab, tabHeader: MatTabHeader, idx: number) {
    const result = confirm(`Do you really want to leave the tab ${idx}?`);

    return result && MatTabGroup.prototype._handleClick.apply(this.tabs, arguments);
  }
}

Ng-run Example

like image 110
yurzui Avatar answered Dec 05 '22 19:12

yurzui