I am trying to use :host
with Encapsulation.None
but the styles are not applying.
Should this work and if so how?
Example below, there are 2 child components that are identical except for Encapsulation.None (where the host styling is not applied) and Encapsulation.Emulated (where the host styling is applied).
Both have css:
:host {
color:red;
}
Output is:
Stackblitz: https://stackblitz.com/edit/angular-kvjma8?file=src%2Fapp%2Fapp.component.html
ViewEncapsulation.None. Angular does not apply any sort of view encapsulation meaning that any styles specified for the component are actually globally applied and can affect any HTML element present within the application. This mode is essentially the same as including the styles into the HTML itself.
View encapsulation defines whether the template and styles defined within the component can affect the whole application or vice versa. Angular provides three encapsulation strategies: Emulated (default) - styles from main HTML propagate to the component.
There are several ways to add styles to a component: By setting styles or styleUrls metadata. Inline in the template HTML. With CSS imports.
To turn an Angular component into something rendered in the DOM you have to associate an Angular component with a DOM element. We call such elements host elements.
The component selector can be used as the CSS selector to style the host element when the encapsulation is set to ViewEncapsulation.None
:
/* With ViewEncapsulation.Emulated, use :host selector */
:host {
color: red;
}
/* With ViewEncapsulation.None, use component selector */
app-child-encapsulation-none {
color: green;
}
See this stackblitz for a demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With