In this article we are creating dark and light mode toggle in angular. here we are using service to create toggle.
Step : 1 : create theme-service file and put below code :-
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ThemeService { constructor() { } white: string = '#ffffff'; black: string = '#141313'; public darkMode$: Subject<boolean> = new Subject<boolean>(); isThemeDark = this.darkMode$.asObservable(); setDarkTheme(isThemeDark: boolean) { this.darkMode$.next(isThemeDark); if (isThemeDark == true) { document.body.style.background = this.black localStorage.setItem('dark', 'true'); } else { document.body.style.background = this.white localStorage.setItem('dark', 'false'); } } }
Step : 2 : Now put below ts code in app.component.ts file :-
import { AfterViewInit, Component } from '@angular/core'; import { Observable } from 'rxjs'; import { ThemeService } from './_services/auth.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements AfterViewInit { isThemeDark!: Observable<boolean>; theme: boolean = false constructor( private themeService: ThemeService ) { } ngOnInit() { this.isThemeDark = this.themeService.isThemeDark; } toggleDarkTheme(checked: any) { checked.checked == true ? this.theme = true : this.theme = false console.log(this.theme) this.themeService.setDarkTheme(checked.checked); } ngAfterViewInit(): void { document.getElementsByClassName("mat-checkbox-inner-container-no-side-margin")[0].classList.add("d-none") } }
Step : 3 : Now put below html code in app.component.html file :-
<div class="wrapper"> <h3 class="text-success">Creating Dark And Light Mode toggle In Angular</h3> <div class="custom-control custom-switch"> <h1 class="mb-0 text-warning underline" *ngIf="theme">Dark Mode :</h1> <h1 class="mb-0 underline" *ngIf="!theme">Light Mode :</h1> <mat-checkbox class="custom-control-input" id="darkMode" [checked]="isThemeDark | async" (change)="toggleDarkTheme($event)"> <label class="custom-control-label" for="darkMode"></label> <img *ngIf="theme" src="https://raw.githubusercontent.com/talohana/angular-dark-mode/master/src/assets/moon.svg" /> <img *ngIf="!theme" src="https://raw.githubusercontent.com/talohana/angular-dark-mode/master/src/assets/sun.svg" /> </mat-checkbox> </div> </div>
Step : 4 : run your application using ng serve
Output :-