Files
Showy/frontend/src/app/core/services/theme.service.ts
T
2024-04-21 17:05:22 +01:00

43 lines
904 B
TypeScript

import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ThemeService {
private theme: 'light' | 'dark' = 'light';
constructor() {
this.loadTheme();
}
toggleTheme(): void {
this.theme = this.theme === 'light' ? 'dark' : 'light';
this.applyTheme();
}
private loadTheme(): void {
if (localStorage.getItem('theme')) {
this.theme =
(localStorage.getItem('theme') as 'light' | 'dark') || 'light';
} else {
this.theme = this.getSystemTheme();
}
this.applyTheme();
}
private applyTheme(): void {
document.documentElement.setAttribute('data-bs-theme', this.theme);
localStorage.setItem('theme', this.theme);
}
private getSystemTheme() {
if (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
)
return 'dark';
return 'light';
}
}