Search code examples
cssangularbackground-color

Angular 6: How to change page background-color dynamically


I work on an Angular 6 app (with Bootstrap 4) and need to change the page background color depending on which page the user enters. Default is white, but for login and registration screen the page color needs to be blue.

What I found so far:

  • in ngAfterViewInit() using this.elementRef.nativeElement.ownerDocument: this approach makes the app more vulnerable to XSS attacks and I want to avoid that.
  • Set View Encapsulation to None in app.component.ts: this way I can set the body color in the app.component, that is 1 step forward.

So, now I have in my app.component.css:

body {
  background-color: blue;
} 

Question: How can I change that color value (in app.component) using a variable?

  • With [ngStyle] I can not reach the body background-color.
  • Maybe using a css variable? but how can I change the value of that css variable dynamically?
  • I'm new to Sass, but might this offer a solution?

My question is different from the other question on this subject as I need to be able tochange the color value dynamically.


Solution

  • use render2 and set class to body using document object

    app.component.ts

    constructor(private renderer: Renderer2) {
    this.renderer.addClass(document.body, 'body-class');
    }
    

    Note: if you are toggling classes, just remove previous class before assigning new class