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

Lor*_*idi 7 tabs angular-material angular

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

Ema*_*aro 8

我使用了 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]);
        }
    };
}
Run Code Online (Sandbox Code Playgroud)


H.A*_*.Al 1

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

最后我在这里发现了一些与(selectedTabChange)="tabChanged($event)"已使用的不同的东西:

  1. 添加@ViewChild('tabGroup') tabs: MatTabGroup;到您的班级;
  2. 将 #tabGroup 添加到<mat-tab-group #tabGroup> .. </mat-tab-group>您的 HTML 代码中。
  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;    
}
Run Code Online (Sandbox Code Playgroud)

干杯!


归档时间:

查看次数:

2936 次

最近记录:

5 年,1 月 前