DEV Community

Em
Em

Posted on

3 ways to change body background color in different components in Angular 15

Coding apps, as a beginner, lead me to Dev, probably more than 100 times, in search for answers related to many problems beginners face while developing. Did I found my answers? Absolutely YES. This is why I am here now. Sharing small steps for beginners, like me, who are on the same path. Path of evolving, learning growing as a developer.

Here are 3 ways that worked for me, when I had to change body background color with different paths.

Disclaimer: I am not saying these are perfect solutions, nor the only ones, these are just the solutions that worked for me.

Let's begin - creating app and components

For the sake of this post and learning how to change background color in different ways we will make an Angular app with 4 different components. Before this step make sure you have properly installed node.js and Angular cli. You can check this link to learn how to do this.

ng new angular-background-color

We will call our app Angular Background Color.
Now let's make 4 different components.

ng g c One --standalone --skip-tests
ng g c Two --standalone --skip-tests
ng g c Three --standalone --skip-tests
ng g c Four --standalone --skip-tests

Including Bootstrap in the app

You can include bootstrap in the app in any way you like (look at the Bootstrap documentation). I decided to install Bootstrap using:
npm install bootstrap
command and including the Bootstrap in angular.json file. Edit the styles and scripts sections like this:

"styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
            ],
"scripts": [
              "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
            ]
Enter fullscreen mode Exit fullscreen mode

1. Setting global styles

We are going to set some global styles in the styles.css:

body {
/* Default background color */
  background-color: #f8ffcc;
}

h1 {
  color: #ae4cd5;
  border-radius: 5px;
  font-weight: 700;
}

small{
  color:#ae4cd5;
  text-transform: uppercase;
  font-weight: 400;
}
Enter fullscreen mode Exit fullscreen mode

2. Component One

one.component.html

The Html part of each component will be similar, containing just one Title, subtitle and button.

<div class="container-fluid">
  <div class="row mt-5">
    <div class="col text-center">
      <h1 class="one p-2">Hello from component 1</h1>
    </div>
  </div>
  <div class="row subtitle text-center mt-1">
    <small>This is the inital background color of body tag.</small>
  </div>
  <div class="row buttons mt-5">
    <div class="col text-center">
      <a class="btn two" [routerLink]="['/two']">Component Two</a>
    </div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

one.component.css

.btn.two {
  width: 80%;
  background-color: #ae4cd5;
  border-radius: 5px;
  border: 1px solid #efb2e2;
  color: #f8ffcc;
  text-transform: lowercase;
  font-weight: bold;
  box-shadow: rgba(129, 0, 202, 0.15) 1.95px 1.95px 2.6px;
}
Enter fullscreen mode Exit fullscreen mode

3. Component Two

two.component.html

We will only change few things.
Title:
<h1 class="one p-2">Hello from component 2</h1>
Subtitle:
<small>Body color changed using Element Ref.</small>

Button link and text:
<a class="btn three" [routerLink]="['/three']">Component Three</a>

two.component.css

Change the background color, color and border color of the button to:

.btn.three{
  background-color: #f1ff99;
  border: 1px solid #e688d4;
  color: #ae4cd5;
}

Enter fullscreen mode Exit fullscreen mode

4. Components 3 and 4

We will now do the same changes like in component 2 but adjust them for component 3 and 4.

html changes

  • Component 3 title: <h1 class="one p-2">Hello from component 3</h1>
  • Component 3 subtitle: <small>Body color changed using DOCUMENT from angular/common.</small>
  • Component 3 button: <a class="btn one" [routerLink]="['/four']">Component Four</a>
  • Component 4 title: <h1 class="one p-2">Hello from component 4</h1>
  • Component 4 subtitle: <small>Body color changed using css :host-context() function.</small>
  • Component 4 button: <a class="btn four" [routerLink]="['/']">Component One</a>

css color changes

  • Component 3 button colors:
.btn.one{
  background-color: #efb2e2;
  border: 1px solid #E688D4;
  color: #ae4cd5;
}
Enter fullscreen mode Exit fullscreen mode
  • Component 4 button colors:
.btn.four {
  background-color: #f8ffcc;
  border: 1px solid #f1ff99;
  color: #e688d4;
}
Enter fullscreen mode Exit fullscreen mode

- USING ELEMENT REF TO CHANGE BACKGROUND COLOR

This is the first way we will use to change the background color for Component 2. Once the user clicks the button in the component 1 the component 2 loads with different body background. Let's use ElementRef to achieve this. In two.component.ts lets import ElementRef:
import { ElementRef } from '@angular/core';

Than let's inject it in the constructor:
constructor(private elementRef: ElementRef){}

Now let's use the element ref to change background color on component initialization:
ngOnInit() {
this.elementRef.nativeElement.ownerDocument.body.style.backgroundColor ='#EFB2E2';
}

And finally let's change the background color back to the default one when the component is being destroyed:
ngOnDestroy() {
this.elementRef.nativeElement.ownerDocument.body.style.backgroundColor =
'#F8FFCC';
}

Don't forget to import onDestroy:
import { OnDestroy } from '@angular/core';

We could also use ElementRef to add a class to body element and set different color in the global styles using the body.classWeAdded selector.

- USING DOCUMENT TO CHANGE BACKGROUND COLOR

Let's use DOCUMENT form angular/common to change the background color of the body tag on component initialization.
Once the user clicks the button 'component three' the component 3 loads and the background color is changed. First step is to import DOCUMENT:
import { DOCUMENT } from '@angular/common';
Than we need to inject it into the component constructor:
constructor(@Inject(DOCUMENT) private _doc: any) {}
And use it on component initialization to change the color:

ngOnInit() {
    this._doc.body.style.background = '#F1FF99';
  }
Enter fullscreen mode Exit fullscreen mode

And on component destroy to set the color back to the initial color:

  ngOnDestroy() {
    this._doc.body.style.background = '#F8FFCC';
  }
Enter fullscreen mode Exit fullscreen mode

- USING CSS :HOST-CONTEXT()

We can also use css :host-context() function to achieve the same result. In this case we do not need to import anything into the component we just need to declare the class to the body element in the index.html and target that class through the functon. This is done in the component 4 css file by adding:

:host-context(body.componentFourColor) {
  background-color: #ea9adb !important;
  display: block;
  height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

It is very important to use the height of 100vh and display property to block here because otherwise it overrides the body color by applying it only to the height of the component it self.

Adding routes

Our application can not work without routes and we will add them now by making routes.ts file in app folder and pasting this code in it:

import { Routes } from '@angular/router';
import { FourComponent } from './four/four.component';
import { OneComponent } from './one/one.component';
import { ThreeComponent } from './three/three.component';
import { TwoComponent } from './two/two.component';

const routeConfig: Routes = [
  {
    path: '',
    component: OneComponent,
    title: 'Component One',
  },
  {
    path: 'two',
    component: TwoComponent,
    title: 'Component Two',
  },
  {
    path: 'three',
    component: ThreeComponent,
    title: 'Component three',
  },
  {
    path: 'four',
    component: FourComponent,
    title: 'Component four',
  },
];

export default routeConfig;
Enter fullscreen mode Exit fullscreen mode

We also need to import RouterModule into every component so we can use routerLink:
import { RouterModule } from '@angular/router';

This is it. Our application can now be served and every component will have a different color.
Another option for us would be to check the active route and according to that change the background color of the body tag. I am yet to try this approach.

If you need to see the results you can check out the StackBlitz project for this tutorial:

I hope you can find this helpful :)

Top comments (0)