To implement this feature, you can utilize the power of BehaviourSubject from RXJS. Initially, set it to false and switch between light and dark mode by calling the next() method to update the behaviour subject. Make sure to subscribe to the BehaviourSubject variable on initialization to handle the response effectively.
For reference and detailed information, check out BehaviourSubject.
I have personally incorporated the dark mode feature in one of my projects showcased at telivic.com. You can find the implementation approach I used on that site. Hopefully, this solution will work well for you too.
addDark(){
document.getElementById('nav').classList.add('dark');
document.getElementById('box').style.backgroundColor = "#35363A";
document.getElementsByTagName("BODY")[0].classList.add('dark');
document.getElementById('modal').style.backgroundColor ="bisque";
if(this.service.flag){
document.getElementById('opt').classList.add('dark');
}
document.getElementById('gen').style.color="white";
}
removeDark(){
document.getElementById('nav').classList.remove('dark');
document.getElementById('box').style.backgroundColor = "#fff";
document.getElementsByTagName("BODY")[0].classList.remove('dark');
document.getElementById('modal').style.backgroundColor ="white";
if(this.service.flag){
document.getElementById('opt').classList.remove('dark');
}
document.getElementById('gen').style.color="black";
}
/*Binded my switch to this function I have used service so that user dark/light mode preference can be processed in other pages also.*/
darkMode(){
this.dark = !this.dark;
this.userService.setMode();
if(this.dark){
this.addDark();
}else{
this.removeDark();
}
}