I've got a custom component <ui-title>
that I wish to style differently based on what its direct parent element is.
For example, if it appears within <ui-section>
, style it YELLOW. Within <ui-card>
style it BLUE. If it appears anywhere else, style it GREEN.
Here's what I've tried:
:host {
background-color: green;
}
:host-context(ui-card) {
background-color: blue;
}
:host-context(ui-section) {
background-color: yellow;
}
This doesn't work because if an element is nested within both <ui-section>
and <ui-card>
because both sets of styles would be applied. I wish to apply a set of styles based strictly on the direct parent of the:host element.
Here's a StackBlitz that shows my issue.
I found that you can combine :host
and ::ng-deep
from this answer after few hours of searching and trying different combination of ::ng-deep
, :host
and :host-context
.
https://stackblitz.com/edit/angular-ivy-yf1uff?file=src/app/ui-title/ui-title.component.css
So just moved the style related to the ui-card
and ui-section
to their own stylesheet and combine :host
and ::ng-deep
with child selector >
:host > ::ng-deep ui-title {
font-size: 10px;
background-color: blue;
}
:host > ::ng-deep ui-title {
background-color: yellow;
}
:host {
display: block;
padding: 5px;
border-radius: 10px;
background-color: green;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.