Skip to content

Instantly share code, notes, and snippets.

@muhammadawaisshaikh
Created May 9, 2020 09:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save muhammadawaisshaikh/9b62e76a3827a7478c59dc30e0eaa8a1 to your computer and use it in GitHub Desktop.
Save muhammadawaisshaikh/9b62e76a3827a7478c59dc30e0eaa8a1 to your computer and use it in GitHub Desktop.
Creating a Dark & Light Toggle Mode on your Angular App
<div class="text-right">
<div class="custom-control custom-switch">
<mat-checkbox type="checkbox"
class="custom-control-input"
id="darkMode"
[checked]="isThemeDark | async"
(change)="toggleDarkTheme($event)">
<label class="custom-control-label" for="darkMode"></label>
<a class="text-capitalize">Dark Mode</a>
</mat-checkbox>
</div>
</div>
import { Component, OnInit } from '@angular/core';
import { ThemeService } from '../../shared/services/theme/theme.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html',
styleUrls: ['./sample.component.scss']
})
export class SampleComponent implements OnInit {
isThemeDark: Observable<boolean>;
constructor(
private themeService: ThemeService
) {}
ngOnInit() {
this.isThemeDark = this.themeService.isThemeDark;
}
toggleDarkTheme(checked) {
this.themeService.setDarkTheme(checked.checked);
// console.log("checked >", this.isThemeDark);
console.log("checked >", checked.checked);
}
}
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ThemeService {
white: string = '#ffffff';
black: string = '#141313';
private _themeDark: Subject<boolean> = new Subject<boolean>();
isThemeDark = this._themeDark.asObservable();
constructor() { }
setDarkTheme(isThemeDark: boolean) {
this._themeDark.next(isThemeDark);
if (isThemeDark == true) {
console.log('Dark Used');
document.documentElement.style.setProperty('--white-color', this.black);
document.documentElement.style.setProperty('--black-color', this.white);
localStorage.setItem('dark', 'true');
}
else {
console.log('Light Used');
document.documentElement.style.setProperty('--white-color', this.white);
document.documentElement.style.setProperty('--black-color', this.black);
localStorage.setItem('dark', 'false');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment