Styling Components Using :host CSS Selector

Styling Components Using :host CSS Selector

Use the :host pseudo-class selector to target styles in the element that hosts the component (as opposed to targeting elements inside the component’s template).

Source:

<!-- demo.component.html -->
Demo component!
<!-- demo.component.css -->
:host {
  display: block;
  border: 1px solid black;
}

Result:

Capture.PNG

The :host selector is the only way to target the host element. You can’t reach the host element from inside the component with other selectors because it’s not part of the component’s own template. The host element is in a parent component’s template.

Use the function form to apply host styles conditionally by including another selector inside parentheses after :host.

The next example targets the host element again, but only when it also has the active CSS class.

Source:

<!-- app.component.html -->
<app-demo></app-demo>
<app-demo class="active"></app-demo>
<!-- demo.component.html -->
Demo component!
/* demo.component.css */
:host {
  display: block;
  border: 1px solid black;
}

:host(.active) {
  border-width: 3px;
}

Result:

Capture.PNG Thanks, Keep learning!