kushal Baldev
kushal Baldev

Reputation: 769

Change angular material material theme dynamically

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..!!

Upvotes: 7

Views: 11413

Answers (2)

Mohammadreza Askari
Mohammadreza Askari

Reputation: 583

@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.

Upvotes: 0

Omar Arturo
Omar Arturo

Reputation: 185

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

Upvotes: 10

Related Questions