Hi there, I need help:
I need to switch between light and dark mode on metronic angular template without refreshing the page, is there a way on doing that?
I've noticed that there is an injectable service that sets the mode on localStorage but afterwards it reloads the page. I need it to toggle without the dropdown also, only clicking on it.
I couldn't find any topics in the KeenThemes docs or forum.
Angular version: 14.0.0
Metronic template: demo1
Code snippet from the service:
public switchMode(_mode: ThemeModeType) {
if (localStorage) {
const updatedMode = _mode === "system" ? systemMode : _mode;
localStorage.setItem(themeModeLSKey, updatedMode);
localStorage.setItem(themeMenuModeLSKey, _mode);
}
document.location.reload();
}
import { Component, Input, OnInit } from "@angular/core";
import { Observable } from "rxjs";
import { ThemeModeService, ThemeModeType } from "./theme-mode.service";
@Component({
selector: "app-theme-mode-switcher",
templateUrl: "./theme-mode-switcher.component.html",
})
export class ThemeModeSwitcherComponent implements OnInit {
@Input() toggleBtnClass: string = "";
@Input() toggleBtnIconClass: string = "svg-icon-2";
@Input() menuPlacement: string = "bottom-end";
@Input() menuTrigger: string = "{default: "click", lg: "click"}";
mode$: Observable<ThemeModeType>;
menuMode$: Observable<ThemeModeType>;
constructor(private modeService: ThemeModeService) {}
ngOnInit(): void {
this.mode$ = this.modeService.mode.asObservable();
this.menuMode$ = this.modeService.menuMode.asObservable();
}
switchMode(_mode: ThemeModeType): void {
this.modeService.switchMode(_mode);
}
}
It's great that you found a solution! Thank you for sharing your code snippet. We'll consider adding it in future updates to improve the light/dark mode switching in the Metronic Angular template. If you have any more feedback or need further assistance, feel free to let us know!
UPDATE: I've managed to achieve the request by adding another const property inside the switchMode function inside the service that makes the calls to switch between modes:
Code snippet:
public switchMode(_mode: ThemeModeType) {
if (localStorage) {
const updatedMode = _mode === "system" ? systemMode : _mode;
localStorage.setItem(themeModeLSKey, updatedMode);
localStorage.setItem(themeMenuModeLSKey, updatedMode);
localStorage.setItem(themeModeValueKey, updatedMode); <--- THIS LINE ADDED
this.mode.next(updatedMode); <--- THIS LINE ADDED
document.documentElement.setAttribute("data-theme", updatedMode); <--- THIS LINE ADDED
ThemeModeComponent.init(); <--- THIS LINE ADDED
}
}