Issue
I am implementing the option for the tab to remember the last option where the user left off, I am saving the value in localStorage and it works correctly when viewed from the console, however, if the index is for example "2", it always goes to the end no matter what.
Here is my code
<mat-tab-group #tabs animationDuration="0ms" disableRipple [selectedIndex]="indexSelected"
(selectedTabChange)="onTabChanged($event)">
<mat-tab> ... </mat-tab>
<mat-tab> ... </mat-tab>
<mat-tab> ... </mat-tab>
</mat-tab-group>
My ts:
public onTabChanged(tabChangeEvent: MatTabChangeEvent): void {
this.indexSelected = tabChangeEvent.index;
this.localStorage.saveItem('lastTabUser', this.indexSelected);
this.change.markForCheck();
}
And
ngAfterContentInit() {
this.indexSelected = this.localStorage.getSavedItem('lastTabUser') || 0;
this.change.detectChanges();
}
I have a localStorage service (for other uses too)
public saveItem(name: string, value: any): void{
localStorage.setItem(name, JSON.stringify(value));
}
public getSavedItem(name: string): any{
return JSON.parse(localStorage.getItem(name));
}
I use ChangeDetectorRef to detect changes.
and i really don’t understand this behavior, being that I am correctly saving the value of the last tab in the localstorage. Is it something in the AfterContent or AfterView?
Solution
I’ve created a stackblitz reproduction for you, which seems to be working as expected. The only difference is parsing indexSelected
using parseInt()
, removal of change detection since it’s not needed and omitting your service and accessing localStorage directly.
So I assume your issue is linked either to:
- Your LocalStorageService
- Some other logic within the component that you have not posted
If you need further help, reproduce your issue where it’s NOT working on stackblitz.