[英]Angular Material Tab : Prevent tab change of mat-tab-group if the form in current tab is dirty
[英]Angular Material Tab Group - prevent tab change
我使用了 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)"
不同的東西,后者是已使用的:
@ViewChild('tabGroup') tabs: MatTabGroup;
在你的課堂上;<mat-tab-group #tabGroup> .. </mat-tab-group>
。import {MatTabGroup, MatTab, MatTabHeader } from '@angular/material';
到你的班級;this.tabs._handleClick = this.myTabChange.bind(this);
在ngOnInit
函數中;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.