I've noticed that every view in my application has a style file starting like this.
:host {
display: flex;
background-color: blue;
}
div.foo {
background-color: red;
}
It seemed as a wise decision to reduce redundancy and move the general definition to styles.scss. Doing so, I noticed that, while the DIV
styling continued to work as expected, the effect on the pseudo-selector vanished.
Googling gave me that I can't reach the host element from inside the component but it doesn't say anything about altering it from outside of it (which my global styles.scss certainly is). I also found a blog on Angular view encapsulation where details are discussed in depth, however, without mention of the global styles.scss.
Summarizing, I've found a lot of info on handling :host
and a lot of info on applying global styles.scss. However, I've seen rather limited intersection between them. Such an absence of an explicit confirmation implies often that it's infeasible or at least higly discouraged.
Have I misunderstood the point made in the docs? If so, how can I control the :host
speudo-class from my global styles.scss? Or is it a special case of no-no and can't be done?
EDIT
A simple solution using CSS only - :host>* { color: blue; }
in your root component.
Note: This CSS rule will only design components at the first level, If you want to apply to all components of the app you will need to use the original answer
ORIGINAL
I was looking for an elegant way to get what you are asking for, And the best way I've been able to accomplish this is by using SASS.
I did an experiment and saw when inheriting a SASS file with a :host
definition, the :host
selector refers to the component that inherits it.
After a try, the steps below works the same with CSS;
the steps (SCSS / CSS tested):
add new folder under src
named styling
(or whatever you want), add inside new file name _base.scss
(note the underscore)
inside _base.scss
add the style for :host
in your components sass
style, at first line add @import "~src/styling/base";
That's it!