我正在尝试通过点击我的网络应用程序上的开关来实现日/夜功能。
我知道如何使用我的导航菜单将它添加到单个组件中,比方说, 但我需要将它添加到多个组件。
我找到的解决方案之一是使用 ng-deep
但在主 CSS 中这样做感觉有点不对。
我想出的另一个解决方案是创建一个 service
并订阅每个组件中的切换,但这又感觉有点矫枉过正。
我的问题是:我可以通过一次切换更改多个组件的样式吗?
不想使用 JS。
目前,我的 app.component
看起来像这样
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;
//BTW for some reason it does not remove the class but that's a different problem.
}
}
然后在我的模板上:
<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>
然后在 less 中:
:host.night h1 {
transition: all 1s;
color: aliceblue;
}
但这仅适用于 h1,我想知道如何让其他组件随着该切换而改变。
最佳答案
您可以使用服务在多个组件中传播一个值。
例如,这样的服务:
export class ThemeService {
private modeSubject: BehaviorSubject<'day'|'night'> = new BehaviorSubject<'day'|'night'>('day');
public get mode():Observable<'day'|'night'>{
return this.modeSubject.asObservable();
}
public switchMode(newMode:'day'|'night'):void{
this.modeSubject.next(newMode);
}
}
然后,在您的组件中,只需订阅 mode
observable:
...
...
constructor(themeService: ThemeService){
themeService.mode.subscribe(mode => this.theme = mode);
}
...
...
最后,使用 [ngClass]
将主题绑定(bind)到您的模板:
任何实现此逻辑的组件都会随着您的主题模式(白天或夜晚)切换。
请记住,我在这里使用了两个字符串,但您当然可以使用枚举,这些只是为了示例。
关于html - 我可以通过一次切换更改多个组件的样式吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48772405/