angularangular-material

Get actual color from theme, in a javascript variable


I have created, angular material-18 themes and its working ok. Just out of curosity, I want to know if there is any way I can get theme colours in JavaScript variables. I am using theme like this:

.alternate-theme-blue-background {
  background-color: mat.get-theme-color(m3-blue-theme.$light-theme, primary) !important;
}

So what I want is I should get HEX value for m3-blue-theme.$light-theme, primary in a javascript variable like this:

const colorBlue = m3-blue-theme.$light-theme, primary;  and I should get like **#25507c**, in answer.

Solution

  • There's no direct way to extract the colors, but you can use CSS variables to store the theme values and access them in your code.

    SCSS

    :root {
      --primary-color: mat.get-theme-color(m3-blue-theme.$light-theme, primary);
    }
    

    JS

    const primaryColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim();