I'm experiencing an issue with local storage. When I enable the dark mode, everything functions properly and the local storage 'dark' is set to true. However, upon refreshing the page, the local storage remains true but the toggle switches back to unchecked and the theme reverts to white. For the dark theme, I have included bootstrap-dark.
app.sample.component.html:
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault" (change)="toggleDarkTheme()">
<label class="form-check-label" for="flexSwitchCheckDefault">Dark Mode</label>
</div>
sample.component.ts:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ThemeService } from 'src/app/service/theme.service';
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html',
styleUrls: ['./sample.component.css']
})
export class SampleComponent implements OnInit {
checked: boolean = false;
constructor(
private themeService: ThemeService
) {}
ngOnInit() {
}
toggleDarkTheme() {
this.checked = !this.checked;
his.themeService.setDarkTheme(this.checked);
console.log("Dark Theme > ", this.checked);
}
}
theme.service.ts:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ThemeService {
constructor() { }
private _themeDark: Subject<boolean> = new Subject<boolean>();
isThemeDark = this._themeDark.asObservable();
setDarkTheme(isThemeDark: boolean) {
this._themeDark.next(isThemeDark);
if (isThemeDark == true) {
console.log('Dark Used');
document.body.className = 'bootstrap-dark';
localStorage.setItem('dark', 'true');
}
else {
console.log('Light Used');
document.body.className = 'bootstrap';
localStorage.setItem('dark', 'false');
}
}
}