Apply styles from parent

Soumya picture Soumya · Jan 29, 2016 · Viewed 19k times · Source

Suppose I have a component with this template:

<div class="frame">
  <span class="user-defined-text">{{text}}</span>
</div>
<style>
  span { font-size: 3em; }
  .frame { ... }
</style>

How can I merge the styles applied to the component, e.g.

<custom-component [text]="'Some text'">
<style>custom-component { font-weight: bold; }</style>

so that the final output "Some text" is both bold and 3em sized?

Even better is there a way to get the computed styles for the host element, so that, for example, I could apply the background-color of the host to the border-color of some element in my template?

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Jan 29, 2016
  • set encapsulation: ViewEncapsulation.None to allow styles from outside to be applied.
import {Component, ViewEncapsulation} from '@angular/core';

@Component({
  selector: 'custom-component',
  encapsulation: ViewEncapsulation.None
})
export class Custom {
  • use styleUrl to add a CSS file in combination with host selector
:host(.someClass) {
      background-color: blue;
}

<custom-component class="someClass"></custom-component>

to apply styles depending on the class added to the element.