Dev hub
Published in

Dev hub

How I Added Dark Mode in My Personal Blog with Angular, CSS Variables and rxjs

Simple Dark mode toggler in Angular using rxjs and CSS variables!

For the things we have to learn before we can do them, we learn by doing them!
— Aristotle

The dark mode is getting attention like never before! It’s everywhere. Almost all modern web and mobile applications seem to adopt the dark mode one followed by the other. Whatsapp, Facebook, Twitter, Youtube, Stackoverflow, etc… The list can go on.

Implementing dark mode in Angular is fairly simple. You can find tons of articles on the internet explaining dark mode in angular but, using material theming. It is hard to find a simple, non-material guide though 🤷‍♂.

That’s what this article will attempt. We will be implementing dark/light mode in an Angular application without any third-party dependencies. n the journey, you will learn some of the very basic rxjs principles as well 😍.

Why Dark/light modes?

As developers, our end goal is to create applications that users will love. We are constantly making changes to our applications to make it more user friendly easy to use. In this context, if your application requires users to be on the page for a longer time, the dark mode can really help by keeping the user alive on the page. More than just a showpiece, the dark mode can really help users to spend more time on your page and thus giving us a chance to serve the user better.

Dark mode in Angular

Angular material comes with a theming configuration out of the box. But, having no material framework in your project, you will have to find custom-tailored alternatives to do this. In this article, we will be taking help from CSS variables to custom build out dark mode configurator.

Let’s get right to it!

The plan

Let’s plan our implementation in advance. This is how our application looks like without any dark mode capabilities👇.

Initial version without dark mode

The basic idea is to define two sets of CSS variables in our application under two different class selectors(class applied to a high-level wrapper around the top-level component). We then toggle our class names with the help of rxjs. This will result in dynamic color changes to the end-user. Later, we will take help from the localstorage to persist this selection for the next session.

The implementation

The very first step to take is defining our color variables. Go ahead and open up your styles.css(or styles.scss) file and add CSS variables for dark and light modes.

You can use CSS variables in SCSS file as well.

CSS variables defined

I have five variables defined for my unique application. You might have it different. You might only want to use two variables(say dark and light) and toggle. Define this according to your application and need.

The catch here is that, as you see, our variables are defined under these class names. This basically means, just like any other CSS property, that variables are only applied if the elements are children of light-theme or dark-theme classes.

before further discussions, let me bring in my app component(root component).

App component

Pretty typical, huh? You might notice that I have a <div></div> wrapper around the component. Keep this in mind, this will be important later(this element will be referred to as 'theme element’ in the rest of the article).

Now let us create a couple of helper classes that can make use of these variables and apply these to elements that are of concern.

Here’s the subset of what I have created

Note that I have applied background and color properties to the <main> tag, my variables will take effort provided that theme element has either light-theme or dark-theme classes. Let us hard code these classes and check the result.

That’s already half working!

There are a couple of elements on this page that are not dark or light in color(eg. subheadings of cards). You might or might not have these. You can apply classes accordingly from the above set of helper classes to get these working. Anyways, moving on.

Now that we know we can simply switch between classes for the theme element, it’s just a matter of finding a way we can do that dynamically.

We can make use of class binding to do just that. The easiest way to toggle would be to keep a flag on our controller and use *ngIf directive to add/remove the class. There’s a catch here. Our toggle button is going to be present in the header component but the class binding is in our app component. To enable the component to component interaction, we will create a service to manage the toggling state of dark/light modes and then consume this data in app.component.

For this implementation, we will be relying on rxjs and making use of Observables and Behaviorsubject.

You can think of Behaviorsubject like a notifier that can send notifications throughout your application. Any part of your application can subscribe to this data and run some logic on data change.

In our service, we have initialized theBehaviorsubject ,presentThemeSubject, with the initial value as theme-light. Meaning, any part of our application subscribed to this observable, will now receive it’s first value as theme-light. Any user landing on our page will have a light theme by default.

We then created an observable, presentTheme$ which basically act as a wrapper for our presentThemeSubject. This is not a required step. You can directly subscribe to the subject but, this extra step is done to make sure that nowhere in our application we are modifying/ emitting new values by mistake. Note that the subject is made private.

We also have a function changeTheme() function with which we can emit new values.

Now all that is left is to emit values on change of a button(in the header) and subscribe to this observable in our app.component, or precisely, on the theme element.

We will now set up the buttons to toggle

As we are all ready to toggle our themes, we will now subscribe to the presentTheme$ observable in the theme element.

tada!

Our fully functioning angular theme switcher is now ready to be shipped!

Persisting theme selection

We make use of the localstorage API to persist the user selection for the coming sessions. Two simple steps to take here.

  1. Initialize our behaviorSubject with the value from localstorage (if any)
  2. Write values to local storage on the theme selection change event

Go on and edit our theme service as

Want to see the live demo? head over to 👇

Find me on Twitter here

happy hacking!

Originally published at https://bharathravi.com/

--

--

--

Get the latest technology updates in envelop!

Recommended from Medium

Pre-Render A Vue.js App (With Node Or Laravel)

How To Integrate LESS CSS In Magento 2?

How To Integrate LESS CSS In Magento 2?

Why [‘1’, ‘5’, ’11’].map(parseInt) returns [1,NaN,3]?

Here’s How image

Build a Telegram Bot using TypeScript, Node.js, and Telegraf and deploy it on Heroku

An Interesting™️ RxJS Use Case

Fast Creation of Performance Tests Based on SoapUI Project

Redux Basic Indroduction

10 Firefox Dev Tools things that you might not know yet

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bharath Ravi

Bharath Ravi

javaScript | Angular

More from Medium

Is 2021 the end of AngularJS?

How To Create A Data table in Angular 10 Using Bootstrap And Contrast

Angular Best Practices — 2022

Angular

How to Debug Angular Applications in Visual Studio Code