我使用Angular 6应用程序(使用Bootstrap 4),需要根据用户输入的页面更改页面背景颜色。默认为白色,但对于登录和注册屏幕,页面颜色需要为蓝色。
到目前为止我发现了什么:
所以,现在我的app.component.css:
body {
background-color: blue;
}
问题:如何使用变量更改该颜色值(在app.component中)?
我的问题与此主题的其他问题不同,因为我需要能够动态地更改颜色值。
使用render2并使用文档对象将类设置为body
app.component.ts
constructor(private renderer: Renderer2) {
this.renderer.addClass(document.body, 'body-class');
}
注意:如果要切换类,只需在分配新类之前删除上一个类
为什么不根据不同的背景颜色定义一个单独的类?例如:
.blue {
background: blue
}
.green {
background: green
}
.grey {
background: grey
}
然后使用ng-class或ngClass在body
上设置这些类,基于页面使用您的任何约定。这应该相当容易实现。
我喜欢这样做的方法是根据路线为html标签添加一个类。例如,我们在基本布局组件中有一些代码(您可以将它放在根组件中),这在ngOnInit中执行此操作:
let wrapper = ''
const path = this.activatedRoute.snapshot.routeConfig.path
wrapper += this.tidyPath(path)
if (wrapper !== '') wrapper += '-'
const childPath = this.activatedRoute.snapshot.firstChild.routeConfig.path
wrapper += this.tidyPath(childPath)
this.routeWrapperCssClass = wrapper
$('html').addClass(this.routeWrapperCssClass)
这将为您的html标记添加一个类,使其看起来像这样(尽管您可能需要调整此代码以适合您的应用):
<html class="registration">
....
</html>
每当您更改路线时,班级将立即更新。
现在,您可以在主样式表中执行此操作:
body {
background-color: pink;
}
html.registration body {
background-color: yellow;
}
您还可以根据添加到html标记的类隐藏元素,如下所示:
.navbar {
display: block;
}
html.registration .navbar {
display: none;
}
因为您始终知道您所处的路线,所以您可以通过CSS完全控制。
PS你可能想用render2而不是jQuery来做DOM操作 - 看看这篇文章... https://alligator.io/angular/using-renderer2 ...之前从未使用过它,但几乎与jQuery语法完全相同 - 感谢Pratap A.K对此的回答