Angular Material: dark mode

Image for post
Image for post

Hi {{username}}.
Today I want to share with you an example of how I make a light and dark theme for sites using Angular Material.


Complete code you can find on GitHub in ‘main’ branch.

Let’s get it started

First, let’s create a new project with scss as preprocessor and add custom Material.

ng new multiple-theming

Image for post
Image for post

ng add @angular/material

Image for post
Image for post
Custom theme

Magic files

  1. MaterialModule (optional)

In order not to produce basic Material components throughout the project, it is preferable to create a separate module for them.

…src/app > ng g m material

2. LocalStorageService

Represents a service for storing a user’s data in the LocalStorage.

…src\app\services> ng g s localstorage

3. StyleManagerService

Represents a service for *-theme.css files management. The service is able to add and remove style files in HTML using a key.

…src/app/services> ng g s style-manager

4. ThemeService

Monitors theme switching.

…src/app/services> ng g s theme

5. Styles


I’ll explain a little later why this file is needed.




6. angular.json

Dev version, unlike Prod, does not create separate CSS files by default. For the StyleManagerService to work properly, you need to add the

“extractCss”: true

line to angular.json. And also add the theme files to the styles section in angular.json.

By the way, if you are using Angular 10+ then “lazy”: true can be omitted.

7. Theme-picker.component

…/src/app/components> ng g m theme-picker

…/src/app/components> ng g c theme-picker

Since in this tutorial I am switching just between light and dark themes, I will use the mat-slide-toggle.

At this stage, we have redefined all the styles of the Angular Material components, and also created a toggle. Let’s add toggle to the navbar of our application.

…/src/app/components> ng g m navbar

…/src/app/components> ng g c navbar

Add navbar to app.component.html

If you run the application now, you will see that the styles change only on Material components.

Image for post
Image for post

In order to change the styles of your components (for example, the background style and font color in app.component), you need to add ‘@mixin’ to your component.

Image for post
Image for post
scss mixins

To get the value of ‘$ theme’ in ‘@mixin’ your mixin must be added to the file


That’s all, everything should work now 😊

Thanks for reading!


Complete code you can find on GitHub in ‘main’ branch.

JAVA / ANGULAR software engineer

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