0

The user needs to select a 3 colours from a colour picker (primary, warn, and accent).

Then in the second system I need to set those as the Angular Material theming.

As I am fetching those colours from the database and receiving from an observable, would there be a way of changing the theming based on those 3 colours coming from the database using Typescript? Or any other solution?

I tried many things already.

Thanks

RNA
  • 63
  • 2
  • 8

1 Answers1

1

I had to do something similar recently and it's not trivial.

The way to go would require the use of CSS Custom properties.

The trick is to define the material palette with a set of css custom properties.

Cf the doc, a palette is made of 10 + 10 values.

$my-palette: (
 50: --primary-50,
 100: --primary-100,
 200: --primary-200,
 // ... continues to 900
 contrast: (
   50: --primary-constrast-50,
   100: --primary-constrast-100,
   200: --primary-constrast-200,
   // ... continues to 900
 )
);

Then you can define a mat palette with : $my-primary : mat.define-palette($my-palette)

Which is then used in the theme :

$my-theme: mat.define-light-theme((
 color: (
   primary: $my-primary,
   accent: $my-accent,
   warn: $my-warn,
 ),
 typography: mat.define-typography-config(),
 density: 0,
));
Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
  • great answer! same aproach worked for me on angular14, but did you check if it works on angular 15+? they've updated material components and I am not 100% sure that new components aren't using some tricky scss math, that would require pallete values to be values, not some tricky things like css custom properties – Andrei Mar 16 '23 at 23:08
  • Well, I kinda did not understand how to use this to solve my issue. Cos all of this that you said is in css, right? Because as I said, I need to change the theme based on what the user will choose in your backoffice system. So the user will pick up 3 random colours from the colour picker, I then need to use this in another system to set the theme, based on what that used has chosen. And these 3 colours in my case will be stored in the DB, I will fetch it in my angular controller, then change the theme. – RNA Mar 17 '23 at 00:02
  • Yeah sorry the missing bit is that you can set the css variables at runtime with Js ! – Matthieu Riegler Mar 17 '23 at 07:07