1

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.

BizzyBob
  • 12,309
  • 4
  • 27
  • 51

1 Answers1

0

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 >

ui-card.component.css

:host > ::ng-deep ui-title {
  font-size: 10px;
  background-color: blue;
}

ui-section.component.css

:host > ::ng-deep ui-title {
  background-color: yellow;
}

ui-title.component.css

:host {
  display: block;
  padding: 5px;
  border-radius: 10px;
  background-color: green;
}
wei
  • 937
  • 2
  • 14
  • 34