如何在Angular中更改整页背景颜色

Efi*_*sky 19 css background-color angular

我试图在Angular中更改整个页面的背景颜色(在没有框架的情况下使用body或html标签).我找不到最佳实践,如果可能的话,我希望它能在框架内,因为我将在未来几年内构建一个应用程序.

And*_*son 31

如果你使用angular-cli.
应该存在一个全局样式文件.

  • SRC
    • 应用
    • 资产
    • 环境
    • 的index.html
    • styles.css的

在那里你应该能够把你的风格放在例如html { background-color: black; }影响整个页面.

  • 这将无法更改特定组件的背景颜色。 (2认同)

asm*_*mud 24

您可以从任何组件执行此操作.例如:

    export class AppComponent implements AfterViewInit {
       constructor(private elementRef: ElementRef){

       }
       ngAfterViewInit(){
         this.elementRef.nativeElement.ownerDocument.body.style.backgroundColor = 'yourColor';
      }
   }
Run Code Online (Sandbox Code Playgroud)

通过使用this.elementRef.nativeElement.ownerDocument,您可以访问该window.document对象而不违反任何角度约定.当然,您可以直接访问该document对象,window.document但我认为通过它访问它会更好ElementRef.

  • 不好的是,实际上,你无法从 ngOnInit 生命周期钩子访问 dom。我已经更正了我的答案 (2认同)

vov*_*dev 15

一般来说,使用ElementRef可能会使您的应用更容易受到XSS攻击.有关更多信息,请参阅此官方Angular文档.

此外,正如Andresson所建议的那样,在styles.css文件中设置全局样式可能无法解决您的问题,如果您正在使用具有自己的Shadow DOM的多个组件.

使用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
})
Run Code Online (Sandbox Code Playgroud)

接下来,转到app.component.css文件,只需添加背景颜色:

body {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)

此更改将全局影响您的应用.在这里阅读更多相关信息.

  • 顺便说一句,如果我对页面的正文或html样式进行了更改,我仍然看到这些更改在其他页面中也有效。是否仍然只将更改限制在特定页面上? (2认同)

Ric*_*ick 5

不知道为什么没有提到它,但是将它添加到全局 css 文件中效果很好:

body { background-color: red !important; }
Run Code Online (Sandbox Code Playgroud)