0

I have 2 components, a parent and a child. The parent contains the child and uses it to wrap some content and add a title to it. The child component uses transclusion to achieve that.

The parent template looks like:

<div class="parent">
  <child [title]="componentTitle" class="child">
    <p>some content</p>
  </child>  
</div>

The child template looks like:

<div class="child">
  <h2 class="title">{{title}}</h2>
  <ng-content></ng-content>
</div>

When I try to control the styles using the parent component's CSS, I can deal with all the transcluded content simply enough:

.child p {
  background-color: blue;
}

However, I'm unable to get to the title element. In other words, the following rule does not work:

.child h2.title {
  background-color: red;
}

Since parent is the host of child, using :host doesn't work.

Any suggestions ?

ethanfar
  • 3,733
  • 24
  • 43
  • Possible duplicate of [How to style child components from parent component's CSS file?](https://stackoverflow.com/questions/36527605/how-to-style-child-components-from-parent-components-css-file) – Christian Benseler Feb 25 '19 at 19:11
  • @ChristianBenseler I haven't seen that question, you might be right. I was under the assumption that I couldn't set the style due to the transclusion but I guess the problem is even more basic than that. – ethanfar Feb 26 '19 at 05:27

1 Answers1

0

Well, you could do something like this:

::ng-deep {
    .child h2.title {
        background-color: red;
    }
}

I think that is deprecated though. The most appropriate way is to pass an input into the child. I recommend: 1) adding a @Input() titleColor to the child class. 2) .red css style, with background-color: red. to the child css 3) adding a [ngClass]="titleColor" to the child classes h2

bgraham
  • 1,939
  • 1
  • 10
  • 17
  • I thought about using inputs, however, I'm trying to set the color using a CSS variable, which I wasn't able to pass. – ethanfar Feb 25 '19 at 20:13
  • One option might be to use scss. That would allow for global variables – bgraham Feb 25 '19 at 20:17
  • Angular also allows global variables, using the :root pseudo selector, which is what I'm using at the moment. However, the problem is that I don't see a way of passing the name of such a variable to a component and then have that component's CSS evaluate it properly. I've tried passing it as a string as well, which also didn't work – ethanfar Feb 26 '19 at 05:26