DEV Community

Antonio Bertuccio
Antonio Bertuccio

Posted on

Light / Dark Theme - Toggle Switch

Originally built for an Angular project.
Translated to JS to make it available in CodePen.
In Angular 14 the CSS file doesn't change .

-- componente.html

id="darklight-1"
class="theme-switcher d-flex align-items-center justify-content-center"
>
class="sun"
type="checkbox"
[checked]="isLightTheme"
(change)="onThemeSwitchChange()"
/>

-- component.ts

import { Component, OnInit } from '@angular/core';
import { AuthData } from 'src/app/auth/auth-data';
import { AuthService } from 'src/app/auth/auth.service';

@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss'],
})
export class NavbarComponent implements OnInit {
utente!: AuthData | null;
public isLightTheme = true;

constructor(private authSrv: AuthService) {}

ngOnInit(): void {
this.authSrv.user$.subscribe((_user) => {
this.utente = _user;
});
}

logout() {
this.authSrv.logOut();
}

onThemeSwitchChange() {
this.isLightTheme = !this.isLightTheme;

document.body.setAttribute(
  'data-theme',
  this.isLightTheme ? 'light' : 'dark'
);
Enter fullscreen mode Exit fullscreen mode

}
}

Top comments (0)