这似乎是一个相当常见的问题,即在运行时动态地更新样式,并且我无法找到任何关于在编译后尝试覆盖整个 Angular 2 应用程序的 CSS 文件的内容。
我最终所做的(目前)是...
在 GitHub 链接中:
https://github.com/angular/angular/issues/9343
感谢:peteboere
创建了一个类似指令的东西。
import {Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: '[cssProps]',
})
export class CSSPropsDirective {
@Input() cssProps: any;
constructor(private element: ElementRef) {}
ngOnChanges({cssProps})
{
if (cssProps && cssProps.currentValue)
{
const {style} = this.element.nativeElement;
for (const [k, v] of Object.entries(cssProps.currentValue))
{
style.setProperty(k, v);
}
}
}
}
“不幸的是,这意味着在需要进行样式设置的每个元素上都要放置cssProps,例如:”
<div class="panel-heading" [cssProps]="cssStyling">
然后我创建了一个简单的服务,以JSON格式获取样式,例如:
{--backgroundColor: "black"}
在每个组件的CSS文件中,我使用了自定义CSS属性来处理它们。
background: var(--backgroundColor)
--backgroundColor: #008000;
注意,如果在应用程序根级别执行此操作,则可能不需要针对每个组件CSS文件应用样式,但仍需要将指令应用于要动态设置样式的每个元素。在较低的组件中,ViewEncapsulation将需要设置为NONE。
然后,每10秒钟(目前)进行一次httpClient调用,如下:
import { HttpClient } from '@angular/common/http';
import { Subject, Subscription } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable({providedIn: 'root'})
export class StyleSerivce {
styleChanged = new Subject<any>();
interval = new Subscription();
styles:any;
constructor(private httpClient: HttpClient) { }
retrieveStyleFrom() {
setInterval(() => {
this.httpClient.get('https://serverName/stylesss.json')
.subscribe(data => {
console.log(data);
this.styles = data;
this.styleChanged.next(this.styles);
})
}, 10000);
}
}
我在相关组件中订阅了styleChange事件,如下所示:
this.styleSub = this.styleService.styleChanged.subscribe((styleNow) => {
this.cssStyling = styleNow;
})
通过将cssStyling绑定到我的指令上,当我更新存储JSON的数据库时,我可以动态地更新屏幕...(在10秒后)
这个方法是可行的,但是在每个标签上设置它以使其能够从DB / JSON更新中进行动态更新的痛苦是繁琐的。
我不会把这称为解决初始问题的方法,而是一个痛苦的解决方法。