如何使用有角度的材料保持选项卡状态



我使用的是角度8和角度材质。我有四个选项卡,在每个选项卡中你都可以进行编辑,但如果你从编辑返回到选项卡,则必须选择上次选择的选项卡。

我试着这样做:

export class UIStateService {
private state: UIState;
constructor() {}
setState(state: UIState) {
this.state = state;
}
getState(): UIState {
return this.state ? this.state : { tabState: 1};
}
}
export interface UIState {
tabState: number;
}

在组件中:

ngOnInit(): void {
const state = this.uiStateService.getState();
this.setTabState(state.tabState);
}

setTabState(tabId: number) {
}
getCurrentTabState(): number {
return 1;
}

视图如下:

<mat-tab-group>
<mat-tab>
<ng-template mat-tab-label>
<mat-icon class="interviews">speaker_notes</mat-icon>
<span i18n>Interview reports</span>{{ dossierItemsCountString(itemTypes.Interview) }}
</ng-template>
<ng-container *ngTemplateOutlet="itemList; context: { itemType: itemTypes.Interview }"></ng-container>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>
<mat-icon class="notes">note</mat-icon>
<span i18n>Notes</span>{{ dossierItemsCountString(itemTypes.Note) }}
</ng-template>
<ng-container *ngTemplateOutlet="itemList; context: { itemType: itemTypes.Note }"></ng-container>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>
<mat-icon class="goals">grade</mat-icon>
<span i18n>Goals</span>{{ dossierItemsCountString(itemTypes.Goal) }}
</ng-template>
<ng-container *ngTemplateOutlet="itemList; context: { itemType: itemTypes.Goal }"></ng-container>
</mat-tab>
<mat-tab>
<ng-template mat-tab-label>
<mat-icon class="action-steps">list</mat-icon>
<span i18n>Action steps</span>{{ dossierItemsCountString(itemTypes.ActionStep) }}
</ng-template>
<ng-container *ngTemplateOutlet="itemList; context: { itemType: itemTypes.ActionStep }"></ng-container>
</mat-tab>
</mat-tab-group>

那么我需要改变什么呢?谢谢

可以使用垫子选项卡组的selectedIndex属性设置活动选项卡。

首先,您需要将默认的tabState保存为指向第一个选项卡的0。然后,当用户更改选项卡时,更新tabState。

<mat-tab-group [selectedIndex]="selectedTab"
(selectedIndexChange)="setTabState($event)">
...
</mat-tab-group>

现在,在组件的ngOnInit中获取保存的状态:

export class YourComponent implements ngOnInit {
selectedTab: number = 0;
ngOnInit(): void {
const state = this.uiStateService.getState();
if (state) {
this.selectedTab = state.tabState || 0; // Set to 0 if tabState not present
}
}
setTabState(tabId: number): void {
this.selectedTab = tabId;
this.uiStateService.setState({tabState: tabId});
}
}

希望能有所帮助。

您可以尝试使用[selectedIndex]。这是垫子选项卡组的属性。您可以将选项卡索引保存在一个变量中,并将其绑定到selectedIndex属性。希望这能奏效。

最新更新