Multi Theme CSS with Angular

Nowadays, many of the web applications are offering multiple color themes for their users. The recent example we can take is stackoverflow
Many of the developers were waiting for their favorite dark mode for their favorite place on the internet. I have also tried to do so in one of my angular projects. Today I’ll tell you about it.
It’s all the magic of CSS variable property. CSS has provided us a feature called var(), which allows us to runtime change properties of our CSS elements. The var() function in CSS is used to insert a value for the custom property.

syntax

var( custom_property, value )
where :
custom_proprty
is the name of custom property must start with two dashes (–), which is mandatory.
value
is the optional parameter, which is used if the custom property is invalid. You can use this magic with your SCSS file and any non-angular project where CSS or SCSS is used.

Deep Dive- 

Let’s start with coding in Angular. 
Create a project in Angular, generate components that you want and  design your html. I have created an Interface because of that I can create as well as export themes. You can define as many themes as you want. In my case, I have  ‘Default theme’, ‘Light Theme’, and a ‘Dark Theme’.
Create an interface called Theme and export a class as the default theme of your component. Also, create your favorite themes.
NOTE- In your code, you can create Module for all theme-related files, it will be a better coding practice & project structuring.
Now, In your component’s CSS file, use the magic of var(). Create CSS class and define element properties as – 
.my-custom-button{
background-color: var(--button-bg-color);
border-color: var(--button-border-color);
color: var(--button-text-color);
}
Create a service, import the theme definitions. Define methods to activate your theme.
setDefaultTheme(): void {
this.setActiveTheme(defaultTheme);
}
setDarkTheme(): void {
this.setActiveTheme(dark);
}
setLightTheme(): void {
this.setActiveTheme(light);
}
In the setActiveTheme() method, you have to write a logic that will update the properties of CSS class as below –
setActiveTheme(theme: Theme): void {
this.active = theme;
Object.keys(this.active.properties).forEach(property => {
document.documentElement.style.setProperty(
property,
this.active.properties[property]
);
});
}
And yes, we are ready for it. To change the themes use the components & call the needed method of theme service. I assume you can do that.  You can find this code in GitHub repo given below.  github

Default Theme –

dark theme

Light Theme –

light theme CSS

Dark Theme –

dark theme
Do check the live demo – https://multi-theme-ui.herokuapp.com/

Want to Build Your Multi-theme CSS with Angular?

Related Posts

Leave a Comment

Beneficial Things to Apprehend About Telemedicine Solutions