Mat palette - create on the fly

165 Views Asked by At

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

1

There are 1 best solutions below

3
Matthieu Riegler On

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,
));