Style html,body from web component (Angular 2)

2019-01-14 05:49发布

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.

8条回答
等我变得足够好
2楼-- · 2019-01-14 05:57

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.

查看更多
我命由我不由天
3楼-- · 2019-01-14 05:59

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.

查看更多
你好瞎i
4楼-- · 2019-01-14 05:59

Better to add css file at root level and configure it in angular-cli.json OR add it in index.html . so you can write your reset and global styles and no need to worry about shadow dom and other concepts.

查看更多
不美不萌又怎样
5楼-- · 2019-01-14 06:08

I use this approach in my component, loaded in router-outlet:

      ngOnInit() {
        // Change <body> styling
        document.body.classList.add('align-content-between');
      }

      ngOnDestroy() {
        // Change <body> styling
        document.body.classList.remove('align-content-between');
      }
查看更多
放我归山
6楼-- · 2019-01-14 06:11

I had same issue with margin-top , the way I fixed is

constructor(
    private _renderer: Renderer2,
) {
    this._renderer.removeStyle(document.body, 'margin-top');
}

This worked perfectly for me.

查看更多
戒情不戒烟
7楼-- · 2019-01-14 06:16

I just edited the styles.scss file and it worked for me.

查看更多
登录 后发表回答