7

I am new to angular and wanted to change the angular material themes dyamically ,I know how to make differnt themes that is by making scss file ,define 3 colors, include mat properties and functions, but then I was adding that file refrence statically in angular.json, but if I have many custom angular material themes I want to refrence the css files dynamalically.

So is there any easy quick and rather optimized way to do that?

P.S I have gone through many post and docs but seems to be confusing in order when it comes to change the theme dyamically like for example if I have toggle then how to refrence the different style rather than the default one?

Any answer would be higly appreciated..!!

2 Answers 2

11

One solution is to build the material color palette in real time. These are the necessary steps:

  1. Define the color palette in CSS variables and then access them.
  2. Assign these variables to the material angular theme.
  3. Using the "tinycolor" library we create a service to generate the palette based on a color.
  4. With JavaScript we update the CSS variables in the DOM.

Here you have an example:

https://stackblitz.com/edit/angular-material-theming-playground

Sign up to request clarification or add additional context in comments.

2 Comments

when implementing your solution in angular and app-component.ts complains at runtime that 'tinycolor is not defined' what am I missing?
I am recieving NoSuchMethodError: method not found: 'write$1' on null on the stackblitz
0

@Omar's answer is sounds good to me, but I think updateTheme method is better to be something likes to this:

private updateThemePalette(colors: Color[], theme: string) {
  let _colors: string[] = [];
  colors.forEach((color) => {
    _colors.push(`--theme-${theme}-${color.name}: ${color.hex}`);
    _colors.push(`--theme-${theme}-contrast-${color.name}: ${(color.darkContrast ? 'rgba(0, 0, 0, 0.87)' : 'white')}`);
  });
  let themeEle = document.getElementById('theme-colors');
  if (!themeEle) {
    themeEle = document.createElement('style'); themeEle.id = 'theme-colors';
    document.head.append(themeEle);
  }
  themeEle.innerHTML = `body{${_colors.join(';')}}`;
}

in this way colors are going to set into style tag in head.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.