wlf
wlf

Reputation: 3393

Is it possible to style using :host with Encapsulation.None in 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

Upvotes: 20

Views: 7702

Answers (2)

Jayasurya
Jayasurya

Reputation: 137

The :host selector in CSS is used to select the element that is hosting the component that the CSS is applied to. When you set the ViewEncapsulation property of a component to ViewEncapsulation.None, it disables the mechanism that Angular uses to scope styles to that component, which can cause issues when trying to use the :host selector.

When the ViewEncapsulation is set to ViewEncapsulation.None, Angular will not add any special attribute or class to the elements inside the component's template. This means that any styles you apply to the :host selector will also be applied to any other elements on the page that match the same selector, which can lead to unintended styling.

If you still want to use the :host selector, you can use ViewEncapsulation.Emulated instead of ViewEncapsulation.None. This will enable Angular to emulate the behavior of the shadow DOM and scope your styles to the component, but still allow you to use the :host selector.

Also, you can use element selector with the attribute you added on the host element.

my-comp-name { 
/* styles go here */ 
}

Instead of

:host { 
/* styles go here */
}

Upvotes: 3

Martin Parenteau
Martin Parenteau

Reputation: 73741

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.

Upvotes: 39

Related Questions