I am looking to implement a day/night feature on my web app, triggered by a simple toggle click.
While I can easily add this feature to a single component using the navigation menu, I am faced with the challenge of incorporating it into multiple components.
One workaround I came across is utilizing ng-deep
, but it doesn't seem like the cleanest solution when modifying the main CSS.
Another approach I considered is creating a service
and subscribing to the toggle in each component. However, this method appears to be overly complicated for what I'm trying to achieve.
My main query is: Is there a way to change the style of multiple components with a single toggle switch?
I would prefer not to rely on JavaScript for this task.
Currently, the code snippet from my app.component
involves:
import { Component, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
title = 'Optimus Engine';
version = 'Latest';
day = true;
constructor(private element: ElementRef) {
}
dayNight() {
if (!this.day) {
this.element.nativeElement.classList.add('night');
}
if (this.day) {
this.element.nativeElement.classList.remove('night');
}
this.day = !this.day;
//By the way, there seems to be an issue with removing the class, but that's something I need to troubleshoot separately.
}
}
In the template section:
<div class="toggle-box" (click)="dayNight()">
<input type="checkbox" name="checkbox1" id="toggle-box-checkbox" />
<label for="toggle-box-checkbox" class="toggle-box-label-left"></label>
<label for="toggle-box-checkbox" class="toggle-box-label"></label>
</div>
In the less file:
:host.night h1 {
transition: all 1s;
color: aliceblue;
}
However, this styling only applies to h1 elements, and I am exploring ways to extend this functionality to other components based on the same toggle.