Custom Angular Material multiple themes (guide)
Angular Material 12 brought quite a lot of innovations in creating your own themes. Guys from Angular completely rewrote the styles with sass syntax like @use, sass:map, etc. The idea is the same, but the syntax is different.
If you use Angular Material <12 you can read this → article.
Complete code you can find on GitHub in ‘ angular-material-12+’ branch.
I skipped the project creation step because the only thing needed is that Angular Material should use sass or scss as a preprocessor.
Let’s go through the files we need.
Styles tree
LocalStorageService
To save a user-selected theme, we’ll use LocalStorage.
StyleManager
Represents a service for *-theme.css files management. The service is able to add and remove style files in HTML using a key.
ThemeService
Used to keep track of the current theme.
Default theme init
style.scss
Define the default theme in style.scss.
Styles of your components
components.style.scss
The need for this file is described later in the article.
Color config function
theming.scss
mat-create-color-config function return theme’s color config. Present in project solely to reduce duplicate code.
Styles creation
Well, let’s take a look at creating our own theme using orange-theme.scss as an example. You can find light and dark theme files on GitHub
Don’t forget to add your custom theme files in angular.json
All most done
At this stage, we have redefined the styles of the Angular Material components. Let’s add theme switcher to the navbar of our application.
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. It is preferable to use separate files.
To get the value of ‘$ theme’ in your *.style.scss mixin, you should added it to the file _components.style.scss
That’s all, everything should work now 😊
Thanks for reading!
Complete code you can find on GitHub in ‘ angular-material-12+’ branch.
Add me on Linkedin