You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 ngAfterViewInit with a setTimeout to set selectedTabIndex, 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 activeTabSession function has redundant logic (like resetting selectedTabIndex to 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?

  1. Moved initialization to ngOnInit: This runs before the view renders, so selectedTabIndex is set before the tab group loads—ensuring the correct tab is selected immediately on initial load.
  2. Added tabLabels array: Makes it simple to check if the saved tab exists for the current item and quickly retrieve its index without looping through tab elements.
  3. Simplified getSavedTabIndex: Cleanly handles both scenarios (saved tab exists or not) and updates session storage with the fallback tab if needed.
  4. Removed setTimeout and redundant logic: Eliminates the delay that caused the tab to switch after reload, fixing the core issue.
  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 18:42:28