Skip to content

Instantly share code, notes, and snippets.

@adrian-ub
Created December 29, 2020 17:09
Show Gist options
  • Save adrian-ub/da10ba0ae071c0e211756b26c7a25d0c to your computer and use it in GitHub Desktop.
Save adrian-ub/da10ba0ae071c0e211756b26c7a25d0c to your computer and use it in GitHub Desktop.
TailwindCSS dark mode Angular
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