1
- import { Component , Inject , OnInit } from '@angular/core' ;
2
- import { DOCUMENT } from '@angular/common' ;
3
1
import { MediaMatcher } from '@angular/cdk/layout' ;
2
+ import { DOCUMENT } from '@angular/common' ;
3
+ import { ChangeDetectorRef , Component , Inject , OnInit } from '@angular/core' ;
4
4
import { StorageService } from '../../services/storage.service' ;
5
5
6
6
type Theme = 'light' | 'dark' ;
@@ -18,6 +18,7 @@ export class ThemeModeToggleComponent implements OnInit {
18
18
private readonly document : Document ,
19
19
private readonly mediaMatcher : MediaMatcher ,
20
20
private readonly storageService : StorageService ,
21
+ private readonly changeDetector : ChangeDetectorRef ,
21
22
) { }
22
23
23
24
ngOnInit ( ) {
@@ -32,24 +33,25 @@ export class ThemeModeToggleComponent implements OnInit {
32
33
const preferredScheme = darkSchemeMatcher . matches ? 'dark' : 'light' ;
33
34
const storedTheme = this . getStoredTheme ( ) ;
34
35
35
- this . theme = storedTheme ?? preferredScheme ;
36
- this . setTheme ( this . theme ) ;
36
+ this . setTheme ( storedTheme ?? preferredScheme ) ;
37
37
}
38
38
39
39
toggleTheme ( skipStorage = false ) {
40
- this . theme = this . theme === 'dark' ? 'light' : 'dark' ;
40
+ const newTheme = this . theme === 'dark' ? 'light' : 'dark' ;
41
41
// NOTE: We should skip saving theme in storage when toggle is caused by matchMedia change event
42
42
// Otherwise, once saved, it'll no longer correspond to the system preferences,
43
43
// 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 ) ;
46
46
}
47
47
48
48
private getStoredTheme ( ) {
49
49
return this . storageService . get ( 'theme' ) as Theme | null ;
50
50
}
51
51
52
52
private setTheme ( theme : Theme ) {
53
+ this . theme = theme ;
53
54
this . document . documentElement . setAttribute ( 'mode' , theme ) ;
55
+ this . changeDetector . detectChanges ( ) ;
54
56
}
55
57
}
0 commit comments