我希望使用 Angular 创建一个动态着色系统。我创建了一个服务,它有 4 个字符串、成功、信息、警告、危险以及默认的颜色代码。我想在我的应用程序的根目录下,我假设它在 app.component 中,因为我正在使用路由来注入(inject)此服务并全局覆盖
.btn-warning {
color: #fff; <-- Inject my own color like so (color: AppSettings.ColorSettings.Warning)
background-color: #f0ad4e; <-- Inject my own color
border-color: #f0ad4e; <-- Inject my own color
}
我希望它是动态的,这样如果用户进入设置面板就可以更改这些颜色,并实时查看每个使用这些类的地方的效果。
我看到了 [ngStyle]
但它仅将颜色等特定内容应用于一个元素。
我也看到了 [ngClass]
但我不知道如何创建更像是将类应用于元素的方法的类。
我可以这样做吗?
<html>
<!-- Junk ^ with bootstrap up here -->
<style>{{GetColorSettings()}}</style>
<!-- More stuff -->
</html>
最佳答案
这可能不是最优雅的解决方案,但我真的很喜欢它,因为它的设置非常简单。在我的 app.component 里面我有这个设置。在 GenerateColorSettings 方法中,您需要定义所有不同的颜色,这将需要我进一步扩展 ColorSettings 中的类。一些效果是默认的,:hover, :disabled
constructor(public infoService: InformationService, private configSettings: GlobalConfigSettings)
{
var style = document.createElement('style');
style.innerHTML = this.GenerateColorSettings();
style.id = "DynamicColors"
document.body.appendChild(style);
setTimeout(() =>{
configSettings.ColorSettings.warning = "#fff";
configSettings.ColorSettings.ColorsChanged.emit();
}, 25000);
configSettings.ColorSettings.ColorsChanged.subscribe(() =>
{
var style = document.getElementById('DynamicColors');
style.innerHTML = this.GenerateColorSettings();
});
}
private GenerateColorSettings(): string
{
console.log("Getting color");
return `.btn-warning{
color: #fff;
background-color: ${this.configSettings.ColorSettings.warning};
border-color: ${this.configSettings.ColorSettings.warning};
}
.btn-warning:hover{
color: #fff;
background-color: ${this.configSettings.ColorSettings.warning};
border-color: ${this.configSettings.ColorSettings.warning};
}
`;
}
关于css - Angular 4 In Code 全局覆盖 Bootstrap 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44830586/