Angular 2+ the Selected tab stays selected after i reload the page

2 min read 24-09-2024
Angular 2+ the Selected tab stays selected after i reload the page


When developing applications with Angular 2+, one common requirement is to maintain the state of user interface components across page reloads. A typical use case involves keeping the selected tab active even after the user refreshes the page. Below, we will explore how to accomplish this using local storage, providing you with an easy-to-understand solution.

Original Code Scenario

Consider the following code snippet that represents a simple tab component in Angular:

import { Component } from '@angular/core';

@Component({
  selector: 'app-tabs',
  template: `
    <div>
      <button (click)="selectTab('tab1')">Tab 1</button>
      <button (click)="selectTab('tab2')">Tab 2</button>
      <div>
        <ng-container *ngIf="selectedTab === 'tab1'">
          Content for Tab 1
        </ng-container>
        <ng-container *ngIf="selectedTab === 'tab2'">
          Content for Tab 2
        </ng-container>
      </div>
    </div>
  `
})
export class TabsComponent {
  selectedTab: string = 'tab1'; // Default selected tab

  selectTab(tab: string) {
    this.selectedTab = tab;
  }
}

In this code, when a user clicks on a tab button, the selectedTab variable is updated to display the respective content. However, if the user refreshes the page, the selected tab will revert to the default (tab1), which may not be the desired behavior.

Solution: Using Local Storage

To keep the selected tab active after a page reload, we can utilize the localStorage web API. This allows us to save the selected tab in the browser's local storage and retrieve it upon initialization of the component. Below is the revised code:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-tabs',
  template: `
    <div>
      <button (click)="selectTab('tab1')">Tab 1</button>
      <button (click)="selectTab('tab2')">Tab 2</button>
      <div>
        <ng-container *ngIf="selectedTab === 'tab1'">
          Content for Tab 1
        </ng-container>
        <ng-container *ngIf="selectedTab === 'tab2'">
          Content for Tab 2
        </ng-container>
      </div>
    </div>
  `
})
export class TabsComponent implements OnInit {
  selectedTab: string;

  ngOnInit() {
    // Check local storage for the selected tab
    this.selectedTab = localStorage.getItem('selectedTab') || 'tab1';
  }

  selectTab(tab: string) {
    this.selectedTab = tab;
    // Store the selected tab in local storage
    localStorage.setItem('selectedTab', tab);
  }
}

How This Works

  1. OnInit Lifecycle Hook: The ngOnInit method checks the local storage for a saved value of selectedTab. If it exists, it assigns it to the component's selectedTab property; if not, it defaults to tab1.

  2. Updating Local Storage: Each time a user selects a tab, the selectTab method updates both the selectedTab property and the local storage with the new tab value. This ensures that the selection persists through page reloads.

Practical Example

Let’s say your application has a dashboard with multiple sections. By implementing this approach, users can navigate between different tabs while maintaining their selections, improving their experience significantly.

SEO Optimization

To make this article more search engine friendly, keywords such as "Angular 2+, selected tab, local storage, state management" can be strategically used within headings and throughout the content.

Conclusion

By following the outlined solution, Angular 2+ developers can easily retain the selected tab across page reloads using local storage. This enhances user experience by maintaining stateful components.

Additional Resources

Implementing these practices will not only improve the usability of your application but also familiarize you with efficient state management techniques in Angular. Happy coding!