angular-materialangular9

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


Solution

  • 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