Soumya Soumya - 6 months ago 97
CSS Question

Apply styles from parent in angular2

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 would be a way to get the computed styles for the host element, so that, for example, I could apply the
background-color
applied to the host to the
border-color
of some element in my template.

Answer
  • 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.