Angular 8中mat-tab初始加载记忆选中标签的实现问题
Solution for Initializing MatTabGroup to Saved Tab on Load
Got it, let's fix this issue where your tab doesn't select the saved index on initial load—right now it's waiting for a reload because you're setting the index too late in the component lifecycle. Here's how to adjust your code to get the desired behavior:
Key Issues in Current Implementation
- You’re using
ngAfterViewInitwith asetTimeoutto setselectedTabIndex, which runs after the tab group has already rendered its initial state. That’s why you see the tab switch after load instead of immediately. - The
activeTabSessionfunction has redundant logic (like resettingselectedTabIndexto 0 upfront) that complicates the initialization flow.
Fixed Code
Updated Component TS File
import { Component, OnInit, ViewChild } from '@angular/core'; import { MatTabGroup } from '@angular/material/tabs'; @Component({ // Keep your existing component metadata here }) export class YourComponent implements OnInit { selectedTabIndex: number = 0; @ViewChild('tabGroup') private tabGroup: MatTabGroup; // Define tab labels upfront for easy lookup private tabLabels = ['ProductInformation', 'StocksInformation', 'SpareInformation']; ngOnInit(): void { // Fetch saved tab index immediately when component initializes this.selectedTabIndex = this.getSavedTabIndex(); } // Triggered when user switches tabs tabChanged(event: any): void { const selectedTab = this.tabGroup._tabs.get(event.index); if (selectedTab) { const tabDetails = { tabIndex: event.index, tabName: selectedTab.textLabel }; sessionStorage.setItem('activeTabDetail', JSON.stringify(tabDetails)); } } private getSavedTabIndex(): number { const activeTabDetail = JSON.parse(sessionStorage.getItem('activeTabDetail')); // No saved data? Default to first tab if (!activeTabDetail) return 0; // Check if the saved tab exists in the current item's tab list const tabExists = this.tabLabels.includes(activeTabDetail.tabName); if (tabExists) { // Return the index of the saved tab return this.tabLabels.indexOf(activeTabDetail.tabName); } else { // Fallback to first tab if saved tab doesn't exist for this item const defaultIndex = 0; const defaultTabName = this.tabLabels[defaultIndex]; // Update session storage with the fallback tab sessionStorage.setItem('activeTabDetail', JSON.stringify({ tabIndex: defaultIndex, tabName: defaultTabName })); return defaultIndex; } } }
HTML (No Changes Needed)
<mat-tab-group class="tab-group" #tabGroup (focusChange)="tabChanged($event)" [(selectedIndex)]="selectedTabIndex"> <mat-tab label="ProductInformation"> <div class="tab-content"> ........... </div> </mat-tab> <mat-tab label="StocksInformation"> <div class="tab-content"> ........... </div> </mat-tab> <mat-tab label="SpareInformation"> <div class="tab-content"> ........... </div> </mat-tab> </mat-tab-group>
What Changed?
- Moved initialization to
ngOnInit: This runs before the view renders, soselectedTabIndexis set before the tab group loads—ensuring the correct tab is selected immediately on initial load. - Added
tabLabelsarray: Makes it simple to check if the saved tab exists for the current item and quickly retrieve its index without looping through tab elements. - Simplified
getSavedTabIndex: Cleanly handles both scenarios (saved tab exists or not) and updates session storage with the fallback tab if needed. - Removed
setTimeoutand redundant logic: Eliminates the delay that caused the tab to switch after reload, fixing the core issue. - Improved
tabChanged: Directly uses the tab change event to save accurate tab data to session storage when the user switches tabs.
Now when you select a different list item, the component will immediately load the last saved tab (if it exists for that item), otherwise default to the first tab—no delay or reload required.
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

