If you can imagine wanting to change the theme of your template from light mode to dark after clicking on a button, you will need to ensure that all components in your template also switch themes accordingly. One approach is to create an Angular service and update the property isDarkMode upon button click. You can then subscribe to this property in each component as shown below:
in theme.service.ts
private _isDarkMode = new Subject<boolean>();
isDarkMode = this._isDarkMode.asObservable();
setDarkTheme(isDarkTheme: boolean): void {
this._darkTheme.next(isDarkTheme);
}
in test.component.ts
ngOnInit(): void {
this.isDarkMode = this.themeService.isDarkMode
}
in test.component.html
<div [ngClass]="{'test-dark-mode': isDarkMode }"></div>
To streamline this process, consider using mixins. By creating a mixin for styling the test component template (e.g., @mixin creat-test-theme($theme)) and subscribing to isDarkMode only in app.component.ts, you can avoid repeating subscriptions in every component.
in app.component.ts
ngOnInit(): void {
this.isDarkMode = this.themeService.isDarkMode
}
in app.component.html
<div [ngClass]="{'dark-mode': isDarkMode }"></div>
In your app.component.scss file, define the .dark-mode class and include the mixin to apply the current theme to each component when the dark-mode class is added to the DOM.
.dark-mode {
@include creat-test-theme($dark-theme)
}
This way, with the addition of the dark-mode class, your components will automatically adjust to the selected theme.