theme.service.ts 785 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { Injectable, signal } from '@angular/core';
  2. @Injectable({
  3. providedIn: 'root'
  4. })
  5. export class ThemeService {
  6. private readonly isDark = signal(false);
  7. readonly isDarkMode = this.isDark.asReadonly();
  8. constructor() {
  9. const stored = localStorage.getItem('theme');
  10. if (stored === 'dark') {
  11. this.setDark(true);
  12. }
  13. }
  14. toggle(): void {
  15. this.setDark(!this.isDark());
  16. }
  17. setDark(dark: boolean): void {
  18. this.isDark.set(dark);
  19. const html = document.documentElement;
  20. if (dark) {
  21. html.classList.add('dark');
  22. html.classList.remove('light');
  23. localStorage.setItem('theme', 'dark');
  24. } else {
  25. html.classList.remove('dark');
  26. html.classList.add('light');
  27. localStorage.setItem('theme', 'light');
  28. }
  29. }
  30. }