Angular Material: dark mode

Maxim Sevriukov
3 min readOct 29, 2020

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.

Example: https://irwinjuice.github.io/angular-material-custom-multiple-themes/

Complete code you can find on GitHub in ‘angular-material_11’ 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

SCSS

ng add @angular/material

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

…/src/themes/_components-theme.scss

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

…/src/themes/dark-theme.scss

…/src/themes/light-theme.scss

…/src/styles.scss

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.

Almost done

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.

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.

scss mixins

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

…/src/themes/_components-theme.scss

That’s all, everything should work now 😊

Thanks for reading!

Example: https://irwinjuice.github.io/angular-material-custom-multiple-themes/

Complete code you can find on GitHub in ‘angular-material_11’ branch.

--

--