I’m building an Angular/Ionic app and following the official guidelines for implementing Dark Mode. I’m trying to listen to the device event that’s triggered when the user toggles between dark and light mode on Android (device).
The issue I’m facing is that the event listener is only triggered once, no matter if I’m switching from dark to light or vice versa. After the first time, the body of the listener is never called again.
Here is the code I’m using:
constructor() {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
prefersDark.addEventListener('change', (mediaQuery) => {
console.log('prefersDark.addEventListener fired');
this.toggleDarkTheme(mediaQuery.matches)
});
}
public toggleDarkTheme(shouldAdd) {
document.body.classList.toggle('dark', shouldAdd);
}
I’ve tried also using addListener
instead of addEventListener('change', ...)
, but it didn’t solve the issue. I’ve also tried using the CSS media query approach, but the same problem persists.
@media (prefers-color-scheme: dark) {
:root {
/* dark mode variables go here */
}
}
I’m using angular 12.2.0
, ionic/angular 6.7.0
and capacitor/android 4.7.1
.
By the way, if I run the application on my Windows browser and toggle the dark mode of Windows, it works fine.
Any help would be appreciated. Thanks!