簡體   English   中英

角度材料選項卡組 - 防止選項卡更改

[英]Angular Material Tab Group - prevent tab change

我使用Angular Material Tabs並且需要一個鈎子來檢查用戶是否可以更改選項卡(表單未/保存)。 我找不到任何 API 功能來防止選項卡更改。 有任何想法嗎? 謝謝

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

我面臨着同樣的問題。 在我的情況下,我不會允許用戶移動到另一個選項卡,直到他填寫所有必需的詳細信息。

最后,我在這里發現了一些與(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. 添加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;    
}

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM