I am working on an Angular project's themes. My aim is to implement a sustainable light, dark mode into the project. As you already know, The light mode has it's own styles and so the dark.
To carry this out, I created a services which contains: a boolean darkMode (if true this indicate that darkMode is enabled, false means disabled), two local storage functions(to get and set the darkMode value)
import { Injectable } from '@angular/core';
Import {localStorage} from...
@Injectable({
providedIn: 'root',
})
export class ThemeDataService {
constructor(private local:localStorage) { }
darkMode:boolean=false
getdarkMode(): string {
return local.get...
}
SetdarkMode(darkmode): boolean {
return local.get...
}
}
Then in my components, I fetched the data from the localStorage and make the verications in order to render true to a boolean Var if the value is true on the other hand false(as the localStorage returns values in string format)
import { Component } from '@angular/core';
import { MyService } from './my-service.service';
@Component({
selector: 'app-my-component',
templateUrls:...
StyleUrls:'[... ] '
})
export class ThemeDataService {
darkMode: boolean;
constructor(private theme: ThemeDataService) {
this.darkMode = (this.theme.getdarkMode() == 'true' ) ? true : false ;
}
}
Concerning the styling I used [ngStyle] to style the components dynamically as the styles are essentially background-colors and colors.
Now the problem is that I also have some angular mat-field I need to customize, to customize those mat-field I must select some css classes(those classes does not directly exist in the .html file where the mat-form structure is used).
How could I apply those classes css styles if the darkMode:boolean is true?
Create a service to manage the application's theme state.
Theme Switching Logic
In your HTML template, you can bind the theme toggling logic to a button or any UI element:
Finally, in your root component (usually app.component.html), dynamically load the appropriate CSS file based on the current theme: