Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to style using :host with Encapsulation.None in Angular?

Tags:

css

angular

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:

enter image description here

Stackblitz: https://stackblitz.com/edit/angular-kvjma8?file=src%2Fapp%2Fapp.component.html

like image 789
wlf Avatar asked Apr 07 '20 22:04

wlf


People also ask

What is encapsulation none in Angular?

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.

What does view encapsulation none do?

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.

How we can add style to the particular component in Angular?

There are several ways to add styles to a component: By setting styles or styleUrls metadata. Inline in the template HTML. With CSS imports.

What is host element in Angular?

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.


1 Answers

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.

like image 175
ConnorsFan Avatar answered Sep 18 '22 13:09

ConnorsFan