host + ng-deep + body css not applied

Viewed 3860

I'm trying to make a background color for a specific component being display in the whole component page. It's working fine with

\ ::ng-deep body
 background-color: red

But the things is when i do it like that, the body css is bleeding to the other component page, which become red too. So what i really want to do, is making it local with host. I tried to use

\:host ::ng-deep body

But it wasn't working too, the body background did not change color until i add a specific body tag to my html file component. But i don't want to add a body tag because when i do this, the body size is limited to the element in the page.

I also try to use ViewEncapsulation, but it messed up with all my css.

Any help would be appreciate.

1 Answers

Your first issue (As you found out) with ng-deep is that it bleeds into other pages. And because CSS is lazy loaded inside Angular, everything will be fine until you go to that page, and then head to another page and suddenly everything will be red.

Your second issue is that the :host pseudo selector isn't saying "For this page only" it's saying "For everything inside this component".

So as an example :

If I have a component called MyComponent, and I have css like :

:host ng-deep div {
    background-color :red;
}

And I have a template like so :

<body>
   <app-mycomponent>
       <div></div>
   </app-mycomponent>
   <app-secondcomponent>
       <div></div>
   </app-secondcomponent>
</body>

Only the div inside app-mycomponent would be red. The div inside app-secondcomponent would not be read. Again, :host allows you to ng-deep only within that component.

So why would you need this? Generally it's because you may use a library that you want to style, so you can place it inside a wrapper component and use ng-deep commands freely with the :host prefix, so only the library component inside that wrapper is styled and the rest of your application is unaffected.

So what's the solution? Well the other issue you have is that the <body> tag is actually outside the scope of your angular app. Typically when I've had to edit the body/html tags as a whole, I've just used plain old javascript.

So for example :

export class AppComponent implements OnInit, OnDestroy {
  ngOnDestroy(): void {
    document.body.style.backgroundColor = 'transparent';
  }

  ngOnInit(): void {
    document.body.style.backgroundColor = 'red';
  }
}

It's not the nicest thing in the world, but it's also not terrible. I mostly have to do this when creating modal components that want to stop the body scrolling etc.

For more reading on NG-Deep bleeding : https://tutorialsforangular.com/2020/04/13/the-dangers-of-ng-deep-bleeding/

And how :host works : https://tutorialsforangular.com/2019/12/24/using-the-css-pseudo-element-host-in-angular/

Related