问题:
我需要有关如何在 Angular 中编写机制以在我的应用程序中全局设置组件的“外观”的指导。请注意,我正在尝试学习@ngrx/platform,我认为这将是一个有趣的设计约束;但是,如果它没有意义,我愿意放手。
分解:
我有一个包含许多组件的应用程序正在进行中。我的应用程序中的每个组件目前都有 3 种可能的“外观(L&F)”:
- 早上(棕褐色)
- 下午(白色)
- 傍晚(暗)
请注意,可能会有基于更精细时间的颜色光谱。
这些 L&F 由当前用户的一天中的时间设置,例如,如果用户当前时间是上午 7 点,则计算的 L&F 将设置为“早上”。我在ngrx/store的 Angular 模块中跟踪这个状态SundialModule
,gnomon
它是减速器的机制和getting
状态的动作setting
:
日晷/减速器/gnomon.ts:
import * as gnomon from '../actions';
export interface State {
currentHour: number,
}
const initialState: State = {
currentHour: new Date().getHours()
};
export function reducer(state = initialState,
action: gnomon.Actions) {
console.log(action, 'action');
switch(action.type) {
case gnomon.MORNING:
return {
...state,
currentHour: 6,
};
case gnomon.AFTERNOON:
return {
...state,
currentHour: 12,
};
case gnomon.EVENING:
return {
...state,
currentHour: 7,
};
default:
return state;
}
}
现在我有一个名为Angular Attribute 的指令[sundialTheme]
,它将HostBinding('class') theme = 'light'
在它所在的元素上设置 a 。
日晷/指令/theme.ts
@Directive({
selector: '[sundialTheme]'
})
export class SundialThemeDirective implements OnInit {
@HostBinding('class') theme = 'light';
private gnomon: Observable<any>;
constructor(private store: Store<fromGnomon.State>) {
this.gnomon = store.select<any>('gnomon');
}
ngOnInit() {
this.gnomon.subscribe((theme) => {
if(theme.currentHour >= 7 && theme.currentHour <= 11){
this.theme = 'sepia';
} else if( theme.currentHour >= 12 && theme.currentHour <= 18) {
this.theme = 'light'
} else {
this.theme = 'dark'
}
});
}
}
问题:我的应用程序中的每个组件都需要有这个属性sundialTheme
;此外,每个组件都会订阅this.gnomon = store.select<any>('gnomon');
,这感觉很昂贵/笨拙。最后,顺便说一句,每个组件都需要sundialModule
在每个功能模块中注入,每个组件都需要每天每个时间的主题集:
每个模板的组件就是一个例子。
注意:sundialTheme
属性指令:
<mh-pagination sundialTheme></mh-pagination>
<canvas glBootstrap class="full-bleed" sundialTheme></canvas>
<running-head [state]="(state$ | async)" sundialTheme></running-head>
<menu-navigation sundialTheme></menu-navigation>
<folio sundialTheme></folio>
<mh-footer sundialTheme></mh-footer>
每个具有SundialModule
依赖关系的功能模块:
@NgModule({
imports: [
SundialModule
],
})
export class MenuModule {
}
每个组件 styleUrls 都带有sundial-links
:
注意丑陋的 sundial-morning.scss
@Component({
selector: 'running-head',
templateUrl: 'running-head.component.html',
styleUrls: [
'running-head.component.scss',
'../../../components/sundial/sundial-morning.scss', // This !
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RunningHeadComponent {
}
最后,我有其他方法提供给我:
1) 由于我使用的是 Angular CLI,我可以在全局范围内添加我的样式并让指令在主体上设置一个类。这似乎打破了任何类型的 Web 组件标准。
2)我可以在每个组件中使用工厂加载器styleUrls:[]
;我还没有弄清楚如何实施。
3)我可以遵循材料设计组件架构,将主题直接添加到感觉不太干的组件中?(不过,我还没有深入研究过)
4)我可以为每个组件制作一个自定义装饰器(可能是可行的,但我不确定如何实现)
还有其他建议吗?任何推理的最佳实践?