My goal is to automatically change the theme mode (light/dark) based on the user's device preference using addEventListener. However, I am facing an issue where the event is only triggered once. I am currently working with Ionic and Angular.
Angular CLI: 14.2.3
Node: 16.17.0
Package Manager: npm 8.19.1
OS: win32 x64
Angular: 14.2.3
... cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Package Version
---------------------------------------------------------
@angular-devkit/architect 0.1402.3
@angular-devkit/build-angular 14.2.3
@angular-devkit/core 14.2.3
@angular-devkit/schematics 14.2.3
@schematics/angular 14.2.3
rxjs 6.6.7
typescript 4.7.4
Ionic version: 6.20.1
In service.ts:
setListenerTheme(): void {
window.matchMedia('(prefers-color-scheme: dark)').onchange = (e) => {
console.log("Listening for theme changes")
const buttonToggleTheme = document.querySelector('#themeToggle');
buttonToggleTheme.toggleAttribute('checked');
};
}
toggleTheme(event: any): void {
this.dark_mode = event.detail.checked;
document.body.classList.toggle('dark', event.detail.checked);
}
In app.component:
export class AppComponent implements OnInit {
constructor(
private userService: UserService,
) {}
ngOnInit(): void {
this.userService.setListenerTheme();
}
}