Theming Angular Material

Ole Ersoy
3 min readMay 8, 2022
Image by Ronny Overhate from Pixabay

Scenario

We have the following markup that we will use to demo Angular Material theme creation and switching.

We have placed the end result in this Github Repository in case you wish to clone it and run the code:

git clone git@github.com:fireflysemantics/angular-theming-example.git
cd angular-theming-example
npm i
ng serve -o

Approach

Setup

First create the project angular-theming-example using the CLI.

ng new angular-theming-example --routing --style=scss skipTests=true
cd angular-theming-example

Add Angular Material.

ng add @angular/material

Install our dependencies. We will be using a Firefly Semantics Slice Object Store to house the theme state needed to switch themes.

npm i @fireflysemantics/slice @types/nanoid nanoid

Theme Initialization

Within the src directory create the file themes.scss containing our themes.

The primary color will be mat-indigo with the default hue (color) set to 500 and the lighter and darker hues (colors) set to 200 and 800 correspondingly.

The accent color is set to mat-cyan and Angular material will apply the default weights for the default, lighter, and darker hues since we don’t specify these.

The warn color will be set to mat-deep-orange with a default weight of A200 .

The dark and light themes are defined with the mat-light-theme and mat-dark-theme Sass functions.

After this we need to update styles.scss to include our themes.

Note that we have defined the light-theme and dark-theme classes.

Theme State Service

In order to switch themes we will be emitting the currently select theme class via an Observable<string> . We will use a Firefly Semantics Slice Object Store to initialize and manage this state. The service is located in src/services/state.service.ts .

For more details on how this works see this Youtube.

Or the Object Store Guide.

Application Theme Switching

Within app.component.ts we will initialize the current theme select control with the current theme from our state service and subscribe to the select control valueChanges observable such that we can switch our theme.

Note the methods addThemeClass and removeThemeClasses . These are used to add / remove the current theme class to / from the Angular CDK OverlayContainer . The container is used in the Snackbar, Select and so on components that render overlays .

Finally we have our application template.

Note that within the body element [class] property we assign the current theme using our state service.

<body [class]="s.OS.S.theme.obs | async">

And that’s it. To check out the end result clone the github repository and run it.

git clone git@github.com:fireflysemantics/angular-theming-example.git
cd angular-theming-example
npm i
ng serve -o

--

--