Reputation: 281
I want to apply different full page background-color to my login page with "login" as URL. I use ngAfterViewInit()
and Renderer2 in my login component. When I visit this page and go back to other pages, all the backgrounds of my pages change like my login page, but I want just my login page background-color change.
My Login component using Renderer2
import {AfterViewInit, Component, ElementRef, OnInit, Renderer2} from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, AfterViewInit {
constructor(private elementRef: ElementRef, private router: Router, private renderer: Renderer2) {
this.renderer.setStyle(document.body, 'background-color', 'yellow');
}
ngOnInit() {
}
}
My Login component using AfterViewInit
import {AfterViewInit, Component, ElementRef, OnInit, Renderer2} from '@angular/core'; import {Router} from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, AfterViewInit {
constructor(private elementRef: ElementRef, private router: Router) {
}
ngOnInit() {
}
ngAfterViewInit() {
this.elementRef.nativeElement.ownerDocument.body.style.backgroundColor = '#E7fff4';
}
}
Upvotes: 0
Views: 739
Reputation: 34553
One approach is to toggle the body class using AfterViewInit and OnDestroy using a shared function...
export class LoginComponent implements AfterViewInit, OnDestroy {
toggleBackgroundClass(): void {
document.querySelector('body').classList.toggle('your-class-name');
}
ngAfterViewInit(): void {
this.toggleBackgroundClass();
}
ngOnDestroy(): void {
this.toggleBackgroundClass();
}
}
When your component loads, it will set the background class and when you navigate away, it will remove the class. Your CSS can be as simple as:
body.your-class-name {
background-color: #E7fff4;
}
Upvotes: 1
Reputation: 541
Remove the renderer and elementRef
To limit this to a component, add this in the scss
:host{
backgroundColor = '#E7fff4';
}
Upvotes: 0
Reputation: 3162
Please make the following change:
ngOnInit() {
this.renderer.setStyle(document.body, 'background-color', 'yellow');
}
ngOnDestroy() {
this.renderer.removeStyle(document.body, 'background-color');
// or whatever color you want to change when user move out of login page
}
Upvotes: 1