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?
It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinators (>), which are placed between two CSS selectors.
Let's be clear here, just in case someone is finding this from a search engine: there are no parent selectors in CSS, not even in CSS3.
In a css selector if we need to traverse from parent to child we use > symbol. To get all the immediate children we have to specify * symbol after parent node in the css expression. So the customized css should be parent > *. So for a <ul class="toc chapter">, the css for immediate children shall be ul.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
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 {
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.
I know this is old, but I feel this should be more visible. You could use the /deep/
selector to force a style down through the child component tree into all the child component views. The /deep/
selector works to any depth of nested components, and it applies both to the view children and the content children of the component.
I feel this is much cleaner and easier to implement.
parent.css
/deep/ .class {
background-color: red;
}
https://angular.io/docs/ts/latest/guide/component-styles.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With