角度材质选项卡组-防止更改选项卡

时间:2019-03-07 09:00:15

标签: angular tabs material

我使用Angular Material Tabs,并且需要一个钩子来检查用户是否可以更改选项卡(表单未保存)。我找不到任何API功能来阻止选项卡更改。有任何想法吗?谢谢

2 个答案:

答案 0 :(得分:1)

我使用了AlessHo的解决方案,但是这种方式对我而言并不起作用。我不得不更改分配给_handleClick的函数,返回布尔值并不能解决问题。

这是我的解决方法:

@ViewChild(MatTabGroup) tabs: MatTabGroup;添加到课程中。

请注意使用类型参数代替#tabGroup引用。它也可以使用,但是我们的测试没有。 tabs在测试中未定义,但可与类型选择器一起使用。

接下来,我实现了AfterViewInit,因为在OnInit中,选项卡组没有被可靠地初始化:

ngAfterViewInit(): void {

    // Just to be sure
    if (!this.tabs) {
        throw Error('ViewChild(MatTabGroup) tabs; is not defined.');
    }

    // Returning just a boolean did nothing, but this works:

    // 1. Save the click handler for later
    const handleTabClick = this.tabs._handleClick;

    // 2. Replace the click handler with our custom function
    this.tabs._handleClick = (tab, header, index) => {

        // 3. Implement your conditional logic in canDeactivateTab()
        // (return the boolean here)
        if (this.canDeactivateTab()) {

            // 4. If the tab *should* be changed, call the 'old' click handler
            handleTabClick.apply(this.tabs, [tab, header, index]);
        }
    };
}

答案 1 :(得分:0)

我面临着同样的问题。就我而言,在用户填写所有必填详细信息之前,我不允许用户移动到另一个选项卡。

最后,我发现了与(selectedTabChange)="tabChanged($event)"不同的here,这是已经使用过的东西:

  1. 在课程中添加@ViewChild('tabGroup') tabs: MatTabGroup;
  2. 在您的HTML代码中将#tabGroup添加到<mat-tab-group #tabGroup> .. </mat-tab-group>
  3. import {MatTabGroup, MatTab, MatTabHeader } from '@angular/material';添加到您的班级;
  4. this.tabs._handleClick = this.myTabChange.bind(this);函数中添加ngOnInit
  5. 添加以下功能,该功能允许或不更改标签,并能够获取标签索引号:
myTabChange(tab: MatTab, tabHeader: MatTabHeader, idx: number) {    
    var result = false;    
    // here I added all checks/conditions ; if everything is Ok result is changed to true
    // ==> this way the tab change is allowed.
    return result;    
}

干杯!

相关问题