Hello everyone. I would like to share with you my experiences of how I implemented basic light/dark mode for our Owwly Angular web application.
Background: The last trend for the dark theme option convinced us to introduce a similar approach to our website to fulfill all user's needs - especially mine π.
You can also look at the real website: https://owwly.com to check the described implementation yourself in a real-world use case.
Okay, let's begin.
For start define default theme class, which is going to be your fallback CSS class and default setup for the theme:
Create the definitions for colors and put them to the one list which is going to be used later.
Create an SCSS script to iterate through the colors you defined and generate the right CSS variables:
To provide a smooth transition between both themes, add the CSS class for color and background transitions as below:
Next, create the service responsible for themes toggling. setTimeout is not a pretty solution here, but it does the job. Thanks to it we donβt see the transitions when the page is loaded and style is set to dark. On the other hand, we donβt see page to load light and immediately change to the dark mode. A win-win solution to the rescue.
Initialize the theme toggle service when the app boots up to set previously selected by a user theme.
That's it, now you can use the defined values in your standard component styles as below:
It is a very basic implementation that works for us. I hope you will share your solutions on how you implemented light/dark mode in your angular websites. See ya!
Top comments (9)
Never post code as images, it is a pain in the butt for everyone to copy it, use it, etc. Also, you should never use the document object directly since apps need to use SSR.
@Inject(DOCUMENT) private document: Document
Use this in the constructor.
That being said, great code, it helped a lot.
J
stackblitz.com/edit/dark-mode-with...
Do you have any repo/source code for this ? It would be helpful
Not yet, but I'll prepare a demo angular app with an example.
Cool thanks ! And one more thing you have debug(enable tracing) mode ON for your Routes in production version of owwly.com. You wanna disable it.
Thanks for the info about the routes. I missed that myself. In the below repo you can see the basic example of the dark/light theme implementation. It is not perfect but I hope it will be a good start for further improvements π. github.com/adrianbudzynski/owwly-d...
Thanks for the post and the repo. Awesome read!
hello, what is the theme $ .next for?
Hi, for the basic implementation it is an overengineering and it is unnecessary. But if your UI should do some action during UI change, you can subscribe to this subject.