Dark mode is a must-have feature for your Angular web application. It is easier on the eyes and less draining for your smartphone battery. Here is how you can add a dark mode to your Angular material app in three simple steps.

The end result will be a minimal Angular Material app with an option for a dark mode for users. Here is how it will look like.

Let’s get started then!

Step 1: Add a custom angular material theme

The Angular Material components library comes bundled with a few themes which we can use for your app. But for adding a dark mode, you need to add a custom theme file instead. A sample custom theme looks like the following.

Add this to the styles.scss file of your project.

The important bits here are the primaryaccent, and warn colors. The colors are actually fetched from material design palettes which consist of 19 base colors and their light, dark, and contrast variations. For more details, please refer to the material design color page.

In our case, according to the theme above, we have a teal color as the primary color, pink as the accent color and red as the warn color. This will be our default ‘light’ theme and looks like this.

Image for post

I’ve just added some basic material components, so we can see the effect of the theme changes. Feel free to customize as you want (the code link is available at the end of this post). In case you’re wondering how to layout components using the awesome Flex Layout library, check out my other post on creating a responsive card grid here.

Do you want to use colors not there in the material design color palettes? You can create a theme with custom colors using this super useful online tool and just copy paste the generated theme in your styles as above!

Add dark mode custom theme

For adding the dark mode theme, we just need to add an alternate theme to the theme file.

One last tweak to get the background and foreground color working is to add the class mat-app-background to our parent container in app.component.html.

Now whenever we add this class name to any HTML container, it will apply the dark theme to all of its children. So if we apply the class to the parent div in our app.component.html, this is what we’ll get.

Image for post

#material-design #programming #javascript #dark-mode #angular

Angular Material Dark Mode in 3 steps
40.80 GEEK