I successfully incorporated a theme switcher into my app, enabling users to toggle between different theme/variable.scss files using an on/off switch in the interface.
However, I encountered an issue with storing and retrieving user preferences. While I managed to save the choice to local storage using setItem, I struggled to retrieve it upon refresh/navigation or default to the standard theme if no preference existed.
In my AppComponent.ts file:
export class AppComponent implements OnInit {
currentTheme: string;
constructor( @Inject(DOCUMENT) private document) {
}
ngOnInit() {
if (localStorage.length > 0) {
this.currentTheme = JSON.parse(localStorage.getItem(localStorage.localTheme));
} else {
this.currentTheme = 'Standard contrast';
this.document.getElementById('theme').className = 'standard-theme';
}
}
handleThemeChange(event) {
if (this.currentTheme === 'Standard contrast') {
this.document.getElementById('theme').className = 'high-contrast-theme';
this.currentTheme = 'High contrast mode';
} else {
this.document.getElementById('theme').className = 'standard-theme';
this.currentTheme = 'Standard contrast';
}
localStorage.setItem('localTheme', this.currentTheme);
}
}
The problem arises when trying to update currentTheme
based on what is retrieved from localStorage.localTheme
. Despite the data being returned as expected, currentTheme
ends up being null during debugging.
UPDATE:
this.currentTheme = JSON.parse(localStorage.getItem(localStorage.localTheme));
This particular line seems to be causing the issue. Even though (localStorage.localTheme)
returns a value, this.currentTheme
remains null. Any guidance on resolving this would be greatly appreciated! Thank you!