Search code examples
angularsassangular-materialangular-material2

How to set background palette in custom theme of Angular Material?


I currently define a custom theme finishing with something like:

$my-material-theme: mat.define-light-theme((
    color: (
      primary: $my-material-primary,
      accent: $my-material-accent,
      warn: $my-material-warn,
    ),
    typography: $my-material-font
));


@include mat.all-component-themes($my-material-theme);

All works properly. Still I noticed that some components were using a background-color different from what I used on the application and after some research, though that the following would further customise the theme:

$my-material-theme: mat.define-light-theme((
    color: (
      primary: $my-material-primary,
      accent: $my-material-accent,
      warn: $my-material-warn,
      background: $my-material-background
    ),
    typography: $my-material-font
));


@include mat.all-component-themes($my-material-theme);

, where obviously I defined the new background palette. After testing I see that it doesn't work as mat.define-light-theme seems to be dropping the background key internally and instead using an internal one. I'm not that familiar with Sass or material, and I would like be able to also define the background key introducing the least change on my code, using current version of Angular Material. Thanks in advance.


Solution

  • I just had the same problem. From what I saw the background used is generated internaly as you said. The only way I found to override it, is to set the value in the returned $my-material-theme map.

    Using the map set/get functions is pretty ugly, but with something like this you can override the background value, in this example to "red" :

    $backgroundColor: red;
    $color: map.get($my-material-theme, "color");
    $colorBackground: map.get($color, "background");
    $colorBackground: map.set($colorBackground, "background", 
    $backgroundColor);
    $color: map.set($color, "background", $colorBackground);
    $my-material-theme: map.set($my-material-theme, "color", $color);
    

    Then you can use the modified $my-material-theme the same way you did:

    @include mat.all-component-themes($my-material-theme);