Can you use mat-color with Angulars theme?

Viewed 2576

I am using an Angular theme with my angular 9 app, I have an instance where I want to use mat-color lighter and darker (for color and backgroud-color respectively), I have gotten this to work before with a custom theme but never with an Angular theme.

I have added

background-color: mat-color($color-error, lighter);
color: mat-color($color-error, darker);

to my css where $color-error is a variable I have created. The colors are not coming through to the class.

Any way I can use lighter or darker with mat-color?

Thanks

1 Answers

Here is an example I created on stackblitz on how you can create a theme with angular and define lighter and darker color based on the palette color

Here is the important code :

theme.scss:

@import '~@angular/material/theming';

@include mat-core();

$custom-primary: mat-palette($mat-teal);
$custom-accent:  mat-palette($mat-pink, A200, A100, A400);
$custom-warn:    mat-palette($mat-red);
$custom-theme:   mat-light-theme($custom-primary, $custom-accent, $custom-warn);

@include angular-material-theme($custom-theme);

In this file I create a custom theme and define a light theme.

variables.scss:

@import './theme.scss';

$primary: mat-color($custom-primary);
$primary-lighter: mat-color($custom-primary, lighter);
$primary-darker: mat-color($custom-primary, darker);

Here, I create 3 variables containing primary, lighter and darker colors based on the primary color defined in the theme above.

Note that your lighter and darker colors must be based on a color from your palette. You can't just pick a random color (Even if it is a color from angular. For a red color here, you will have to use $custom-warn). If you still need to lighten or darken a color out of the palette, there is still scss lighten and darken mixins allowing you to do that:

lighten($myColor, 30%), same for darken.

For this theme and variables to works, you need to import theme.scss in styles.scss and wherever you want to use your custom variables, you will have to import variables.scss and that's all.

Related