I'm working on a LoginComponent in Angular 2 that should "restyle" the html and body tags, so I can put in a background image specific for the login page.
But just adding a style for the html, body in my login.css doesn't seem to work.
Is there a way to override the style on the html, body from a component? Or any element for that matter.
I've tried things like:
:host(.btn) { ... }
:host(.btn:host) { ... }
.btn:host { ... }
to style an element from outside the Login component. But nothing seems to work.
You need to change the way your component serves css using ViewEncapsulation. By default it's set to Emulated and angular will
add an attribute containing surrogate id and pre-process the style rules
To change this behavior import ViewEncapsulation from 'angular2/core' and use it in component's metadata:
@Component({
...
encapsulation: ViewEncapsulation.None,
...
})
I'm not sure if this is exactly what you're looking for but this won't leave you with a permanently changed body background-image.
Here is how I did it for something similar. If tou want to impact the body background image for just this page this may work. (I've not tested this fully but it seems to work on windows browsers.)
Inside your component you can just work directly through the DOM when the component gets constructed. When it gets destroyed you can undo the change.
export class SpecialBackground {
constructor(){
document.body.style.backgroundImage = "url('path/to/your/image.jpg')";
document.body.style.backgroundPosition = "center center";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundAttachment = "fixed";
document.body.style.backgroundSize = "cover";
}
ngOnDestroy(){
document.body.style.backgroundImage = "none";
}
}
For your purposes you can use a different function (rather than the constructor) when you button is clicked and you should good to go.
The way I used it is
constructor() {
document.body.className = "bg-gradient";
}
ngOnDestroy(){
document.body.className="";
}
This will dynamically add and remove style from the body for a particular component.