How to Create Your Own Angular 5 Material Theme

Creating your own theme for Angular 5 Material starts with understanding the theming system, which is based on Sass variables and mixins. Angular Material version 5 uses an approach where styles are generated dynamically during the build phase through pre-defined functions. First, you need to make sure that the project uses Sass instead of regular CSS. If the project was originally created using the Angular CLI, all you need to do is rename the styles file to styles.scss and specify the correct path in angular.json.

The basis for a custom theme is to create a new file, such as custom-theme.scss. In this file, you need to import the basic Angular Material tools: @import “~@angular/material/theming”. After that, Sass functions and variables are available to create colors, palettes and other theme parameters. The next step is to create color palettes. Usually, existing Material palettes are taken as a basis and modified using the mat-palette function. For example, mat-palette($mat-indigo) is used for the main color and mat-palette($mat-pink, A200, A100, A400) is used for the accent color. You can also create a completely custom palette by specifying specific values for each hue.

The application theme is then defined via the mat-light-theme or mat-dark-theme function, depending on preference. For example, creating a light theme goes like this: $my-app-theme: mat-light-theme($primary, $accent, $warn), where $primary, $accent, and $warn are the previously defined palettes.

After that, the angular-material-theme mixin is used to connect the theme. Example: @include angular-material-theme($my-app-theme); This mixin needs to be applied in the main styles file of the project so that all Angular Material components automatically apply the defined colors and styles.

It is important to remember that if third-party Material components or CDK library are used in the project, they too will require theme support via their own mixins. It is also possible to create multiple themes and dynamically load them via class switching on the root element of the application, but this requires additional logic in Angular.

Thus, creating your own theme in Angular 5 Material is a process of defining your palettes, generating the theme using built-in functions, and connecting the theme to the application via Sass. This approach allows you to customize the look and feel of components as closely as possible to meet the requirements of a brand or design system.