Created
December 29, 2020 17:09
-
-
Save adrian-ub/da10ba0ae071c0e211756b26c7a25d0c to your computer and use it in GitHub Desktop.
TailwindCSS dark mode Angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, Renderer2, RendererFactory2 } from '@angular/core'; | |
import { Subject } from 'rxjs'; | |
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class DarkService { | |
private renderer: Renderer2; | |
private isDark = false; | |
private matchMediaDark = window.matchMedia('(prefers-color-scheme: dark)'); | |
isDark$ = new Subject<boolean>(); | |
constructor(private rendererFactory: RendererFactory2) { | |
this.renderer = this.rendererFactory.createRenderer(null, null); | |
this.setOrRemoveClass(); | |
this.matchMediaDark.addEventListener('change', () => | |
this.setOrRemoveClass() | |
); | |
} | |
toggle() { | |
if (!('theme' in localStorage)) this.setLocalStorage(''); | |
this.isDark ? this.remove() : this.add(); | |
} | |
private setOrRemoveClass() { | |
this.getDark() ? this.add() : this.remove(); | |
} | |
private add() { | |
this.isDark = true; | |
if ('theme' in localStorage) this.setLocalStorage('dark'); | |
this.renderer.addClass(document.body, 'dark'); | |
this.changeObserver(); | |
} | |
private remove() { | |
this.isDark = false; | |
if ('theme' in localStorage) this.setLocalStorage('ligth'); | |
this.renderer.removeClass(document.body, 'dark'); | |
this.changeObserver(); | |
} | |
private changeObserver() { | |
this.isDark$.next(this.isDark); | |
} | |
private setLocalStorage(data: 'dark' | 'ligth' | '') { | |
localStorage.theme = data; | |
} | |
private getDark() { | |
return ( | |
localStorage.theme === 'dark' || | |
(!('theme' in localStorage) && this.matchMediaDark.matches) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment