How to change whole page background-color in Angular
Asked Answered
C

7

44

I am trying to change the background color for the whole page in Angular(would use body, or html tag when working without framework). and I can't find the best practice for this, I want it to be within the framework if possible since I am building an application for years to come.

Conduce answered 10/10, 2017 at 15:44 Comment(3)
If you're using Angular CLI you can add html and body tags in the styles.css.Prevaricate
put this in "app.component.css" html { background-color: black; } without any effectConduce
Not in app.component.css, in style.css.Or if you set it there(component) then should use something like ::ng-deepEstuarine
S
59

You can do this from any of your component. For example:

export class AppComponent implements AfterViewInit {
    constructor(private elementRef: ElementRef) {}
    ngAfterViewInit() {
        this.elementRef.nativeElement.ownerDocument
            .body.style.backgroundColor = 'yourColor';
    }
}

By using this.elementRef.nativeElement.ownerDocument, you can access the window.document object without violating any angular convention. Of course, you can directly access the document object using window.document but, I think it would be better to access it through ElementRef .

Simulation answered 10/10, 2017 at 15:56 Comment(11)
I tried this, and it didn't work, no errors, just no effect, did I need to change anything here this.elementRef.nativeElement.ownerDocument.style.backgroundColor?Conduce
My bad, actually, you can not access dom from ngOnInit life cycle hook. I've corrected my answerSimulation
I am actually more satisfied with your answer, and its definitely the one that goes into my code, but since Anderson answers hits right the spot and simple, I'll have to approve his, I hope the knowledge of helping me would satisfy you as much as getting the reputation.Conduce
But, @Anderson answer is not what you've asked for. You've asked for a best practice. I definitely could have given you that solution, but instead I've mentioned a solution which could also be a best practice as this way you can change the bg color according to a condition.Simulation
Wouldn't it be great if you at least encourage me with a upvote for my afford.Simulation
Your'e right, didn't knew Anderson's answer was bad practice, I am newbie, and can't up vote, but I approved you.Conduce
It should be noted that once this change is put into effect, it will be true for any other pages as well, even those without this component, etc. The body background color will always be set as this.Dade
This solution seems slow for conditionally adding a background image. There is a visible delay between switching pages. Surely there is a better way?Epilate
I tried all the three ways suggested here...but this way worked as I wanted it . Though the other two options also were successful in turning the whole page to desired color, unfortunately any content that I add to the page using tags like <h1><p> was making the background color darker to that extent which doesn't make page look uniform in color.Fiddlestick
@Simulation I have literally spent hours of seraching for this answer and you saved me just at the moment I gave up. Thank you!Tessietessier
I just want to add, this method sets the background globally. So if you want to avoid this you can set the color again to white in ngOnDestroy().Tessietessier
S
71

If you are using angular-cli.
There should exist a global style file.

  • src
    • app
    • assets
    • environments
    • index.html
    • styles.css

In there you should be able to put your style e.g. html { background-color: black; } to effect the whole page.

Sieve answered 10/10, 2017 at 15:59 Comment(6)
didn't notice that one, thanks, I will wait for asmmahmud's answer, then I'll confirm one of the answers.Conduce
This should be the accepted answer. It is simpler, and seems to fall in line with the intentions of the makers of angular.Plagioclase
this won't able to change background color of a specific component.Pathology
this didn't work for me, the background was black but my components had white backgrounds, I found using body { background-color: black; } worked for me.Coppock
Bootstrap is overriding styles.cssMagma
if your body style changes are overwritten by Bootstrap, change the targeting by adding html before so it's more specific and therefore has higher priority while still not using !important: html body { background-color: black; }Vinificator
S
59

You can do this from any of your component. For example:

export class AppComponent implements AfterViewInit {
    constructor(private elementRef: ElementRef) {}
    ngAfterViewInit() {
        this.elementRef.nativeElement.ownerDocument
            .body.style.backgroundColor = 'yourColor';
    }
}

By using this.elementRef.nativeElement.ownerDocument, you can access the window.document object without violating any angular convention. Of course, you can directly access the document object using window.document but, I think it would be better to access it through ElementRef .

Simulation answered 10/10, 2017 at 15:56 Comment(11)
I tried this, and it didn't work, no errors, just no effect, did I need to change anything here this.elementRef.nativeElement.ownerDocument.style.backgroundColor?Conduce
My bad, actually, you can not access dom from ngOnInit life cycle hook. I've corrected my answerSimulation
I am actually more satisfied with your answer, and its definitely the one that goes into my code, but since Anderson answers hits right the spot and simple, I'll have to approve his, I hope the knowledge of helping me would satisfy you as much as getting the reputation.Conduce
But, @Anderson answer is not what you've asked for. You've asked for a best practice. I definitely could have given you that solution, but instead I've mentioned a solution which could also be a best practice as this way you can change the bg color according to a condition.Simulation
Wouldn't it be great if you at least encourage me with a upvote for my afford.Simulation
Your'e right, didn't knew Anderson's answer was bad practice, I am newbie, and can't up vote, but I approved you.Conduce
It should be noted that once this change is put into effect, it will be true for any other pages as well, even those without this component, etc. The body background color will always be set as this.Dade
This solution seems slow for conditionally adding a background image. There is a visible delay between switching pages. Surely there is a better way?Epilate
I tried all the three ways suggested here...but this way worked as I wanted it . Though the other two options also were successful in turning the whole page to desired color, unfortunately any content that I add to the page using tags like <h1><p> was making the background color darker to that extent which doesn't make page look uniform in color.Fiddlestick
@Simulation I have literally spent hours of seraching for this answer and you saved me just at the moment I gave up. Thank you!Tessietessier
I just want to add, this method sets the background globally. So if you want to avoid this you can set the color again to white in ngOnDestroy().Tessietessier
Y
37

Generally speaking, using ElementRef could make your app more vulnerable to XSS attacks. Refer to this official Angular doc for more information.

Also, setting a global style in your styles.css file, as Andresson has suggested, might not solve your problem if you are working with multiple components which have their own Shadow DOMs.

Here's a safer solution to your problem, using View Encapsulation.
Set View Encapsulation to None (don't forget to import) in your app.component.ts:

import {Component, ViewEncapsulation} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None
})

Next, go to your app.component.css file and simply add your background color:

body {
  background-color: green;
}

This change will affect your app globally. Read more about it here.

Yonita answered 13/7, 2018 at 20:16 Comment(3)
Btw, if i make changes to the body or the html styles in a page i still see those changes are in effect in other pages aswell .Is there anyway to restrict the changes only for that particular page only ?Alves
Why exactly does ViewEncapsulation need to be set to None? I notice that the color doesn't change if we don't set this ViewEncapsulation. (Sorry Angular noob here)Rafter
@DavidChopin this is so that we can remove encapsulation from the DOM. In essence, you are then able to overwrite css styles that have been declared and would not have been able to be changed otherwise.Uhl
N
5

not sure why it's not mentioned, but adding this to the global css file works perfectly:

body { background-color: red !important; }
Naker answered 16/5, 2020 at 18:15 Comment(3)
can you explain what !important does ? Because this solution worked for meTuesday
it just forces the css style to take effect even if other css styles would normally block it.Naker
Bootstrap is overriding styles.cssMagma
F
2

The following solution is another alternative that I came across while I was facing the same problem. For the application to be more adaptable on different platforms we can use Renderer2 class provided by Angular as a service like this:

export class AppComponent {

constructor(private el: ElementRef, private renderer:Renderer2){}

  ngAfterViewInit(){

this.renderer.setStyle(this.el.nativeElement.ownerDocument.body,'backgroundColor', 'yourchoice color');

}

}

More details regarding Renderer2 and its methods can be found here: Render2_Description

Fiddlestick answered 12/9, 2019 at 17:37 Comment(1)
Using renderer instead of direct access is recommended. Read more here: medium.com/better-programming/…Flashy
F
1

You may also want to reconsider the font color:

body
{
  background-color: black !important;
  color:greenyellow;
}
h1
{
  color: aquamarine;
Fineman answered 10/3, 2022 at 18:50 Comment(0)
F
0

You can set the whole content in one div and set style for that div:

<div style="background-color: black; height: 100vh;">

height:100vh will set height to full length of your screen so that the background color will be applied like setting background for whole HTML but just for that page.

Frere answered 2/1, 2023 at 4:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.