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

非 Y 不嫁゛ 提交于 2019-12-05 02:18:14

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/51354135/how-to-conditionally-prevent-user-from-navigating-to-other-tab-in-mat-tab-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!