Skip to content

Commit 4a523ac

Browse files
author
Eugene
committedOct 14, 2024·
fix: theme button don't change on matcher change
1 parent 858a6e4 commit 4a523ac

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed
 

Diff for: ‎src/app/shared/components/theme-mode-toggle/theme-mode-toggle.component.ts

+9-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { Component, Inject, OnInit } from '@angular/core';
2-
import { DOCUMENT } from '@angular/common';
31
import { MediaMatcher } from '@angular/cdk/layout';
2+
import { DOCUMENT } from '@angular/common';
3+
import { ChangeDetectorRef, Component, Inject, OnInit } from '@angular/core';
44
import { StorageService } from '../../services/storage.service';
55

66
type Theme = 'light' | 'dark';
@@ -18,6 +18,7 @@ export class ThemeModeToggleComponent implements OnInit {
1818
private readonly document: Document,
1919
private readonly mediaMatcher: MediaMatcher,
2020
private readonly storageService: StorageService,
21+
private readonly changeDetector: ChangeDetectorRef,
2122
) {}
2223

2324
ngOnInit() {
@@ -32,24 +33,25 @@ export class ThemeModeToggleComponent implements OnInit {
3233
const preferredScheme = darkSchemeMatcher.matches ? 'dark' : 'light';
3334
const storedTheme = this.getStoredTheme();
3435

35-
this.theme = storedTheme ?? preferredScheme;
36-
this.setTheme(this.theme);
36+
this.setTheme(storedTheme ?? preferredScheme);
3737
}
3838

3939
toggleTheme(skipStorage = false) {
40-
this.theme = this.theme === 'dark' ? 'light' : 'dark';
40+
const newTheme = this.theme === 'dark' ? 'light' : 'dark';
4141
// NOTE: We should skip saving theme in storage when toggle is caused by matchMedia change event
4242
// Otherwise, once saved, it'll no longer correspond to the system preferences,
4343
// despite the user not touching the toggle button themselves
44-
if (!skipStorage) this.storageService.set('theme', this.theme);
45-
this.setTheme(this.theme);
44+
if (!skipStorage) this.storageService.set('theme', newTheme);
45+
this.setTheme(newTheme);
4646
}
4747

4848
private getStoredTheme() {
4949
return this.storageService.get('theme') as Theme | null;
5050
}
5151

5252
private setTheme(theme: Theme) {
53+
this.theme = theme;
5354
this.document.documentElement.setAttribute('mode', theme);
55+
this.changeDetector.detectChanges();
5456
}
5557
}

0 commit comments

Comments
 (0)
Please sign in to comment.