【问题标题】:Angular Material Tab Group - prevent tab changeAngular Material 选项卡组 - 防止选项卡更改
【发布时间】:2019-07-29 02:25:43
【问题描述】:

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

【问题讨论】:

标签: angular tabs angular-material


【解决方案1】:

我遇到了同样的问题。在我的情况下,我不允许用户移动到另一个选项卡,直到他填写所有必需的详细信息。

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

  1. 在您的班级中添加@ViewChild('tabGroup') tabs: MatTabGroup;
  2. 在您的 HTML 代码中将#tabGroup 添加到<mat-tab-group #tabGroup> .. </mat-tab-group>
  3. import {MatTabGroup, MatTab, MatTabHeader } from '@angular/material'; 添加到您的班级;
  4. ngOnInit函数中添加this.tabs._handleClick = this.myTabChange.bind(this);
  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;    
}

干杯!

【讨论】:

  • 应该是import { MatTabGroup, MatTab, MatTabHeader } from '@angular/material/tabs';
  • 带有两个小钩子的不错的解决方案:_handleClick(...) 函数返回 void!您的布尔结果将被忽略。您可以通过将此解决方案与模板相结合来解决此问题: [selectedIndex]="selectedTabIndex" 在您的函数中: if (/* your checks here*/) { this.selectedTabIndex = idx;另一个钩子是可以在 ngAfterViewInit 中访问 viewchild。所以把'this.tabs._handleClick = this.myTabChange.bind(this)'放到ngAfterViewInit()中。那是为我做的。
【解决方案2】:

我使用了 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]);
        }
    };
}

【讨论】:

  • 我一直在寻找类似的东西,但是我在运行我的自定义代码时遇到了问题,在进行 tabchange 之后我将如何运行一些东西?
  • 我不确定它是否有效,但我会在第 4 步之后尝试这样做handleTabClick.apply
猜你喜欢
  • 1970-01-01
  • 2020-01-21
  • 2019-02-28
  • 2019-10-29
  • 2018-12-20
  • 2021-09-01
  • 1970-01-01
  • 2018-03-26
  • 2016-01-08
相关资源
最近更新 更多