我想在Angular中改变整个页面的背景色(如果不使用框架,则会使用body或html标记)。我找不到最佳做法,如果可能的话,我希望它在框架内实现,因为我将要建立一个长期应用程序。
我想在Angular中改变整个页面的背景色(如果不使用框架,则会使用body或html标记)。我找不到最佳做法,如果可能的话,我希望它在框架内实现,因为我将要建立一个长期应用程序。
如果你正在使用 angular-cli。
应该存在一个全局样式文件。
在那里,你可以放置你的样式,例如html { background-color: black; }
以影响整个页面。
body { background-color: black; }
对我有用。 - Juan Pablostyles.css
。 - sql_dummyexport class AppComponent implements AfterViewInit {
constructor(private elementRef: ElementRef) {}
ngAfterViewInit() {
this.elementRef.nativeElement.ownerDocument
.body.style.backgroundColor = 'yourColor';
}
}
通过使用this.elementRef.nativeElement.ownerDocument
,您可以访问window.document
对象,而不会违反任何Angular约定。当然,您可以直接使用window.document
访问document
对象,但我认为通过ElementRef
访问更好。
一般来说,使用ElementRef可能会使您的应用程序更容易受到XSS攻击。请参阅此官方Angular文档以获取更多信息。
此外,如Andresson所建议的,在styles.css文件中设置全局样式可能无法解决您的问题,如果您正在使用具有自己Shadow DOMs的多个组件。
这里是一个更安全的解决方案,使用View Encapsulation。
在app.component.ts中将View Encapsulation设置为None(不要忘记导入):
import {Component, ViewEncapsulation} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.None
})
接下来,进入你的app.component.css文件,然后只需添加背景颜色:
body {
background-color: green;
}
此更改将全局影响您的应用程序。在此处阅读更多信息。
不确定为什么没有被提及,但将这个添加到全局CSS文件中就可以完美地解决:
body { background-color: red !important; }
styles.css
。 - sql_dummy我在面对相同问题时,发现了另一种解决方案。为了使应用程序更适应不同的平台,我们可以像这样使用 Angular 提供的 Renderer2
类作为服务:
export class AppComponent {
constructor(private el: ElementRef, private renderer:Renderer2){}
ngAfterViewInit(){
this.renderer.setStyle(this.el.nativeElement.ownerDocument.body,'backgroundColor', 'yourchoice color');
}
}
您可能还需要重新考虑字体颜色:
body
{
background-color: black !important;
color:greenyellow;
}
h1
{
color: aquamarine;
div
中,并为该 div 设置样式:<div style="background-color: black; height: 100vh;">
height:100vh
会将高度设置为屏幕的全长,这样背景颜色就会像为整个HTML设置背景一样应用于该页面。
html { background-color: black; }
不会产生任何效果。 - Efim Rozovsky