6

I have a stencilJS component with two named slots. Is there a way to determine if the slots have been assigned values? For instance, the code snippet below show named slots for "logo" and "menu." How can I check inside the component if both named slots are not empty? Ideally I want to check from inside the component and during componentWillMount() . Thank you.

  <koi-menu breakpoint="768" userToggled="false">
      <div class="logo__header " slot="logo"><img src="assets/images/logo.png" /></div>

      <ul class="nav__wrapper list mw8-ns center-m" slot="menu">
        <li class="nav__listitem"><a class="ttu nav__link" href="???">Why Live Grit</a></li>
        <li class="nav__listitem"><a class="ttu nav__link" href="???">Clients</a></li>
        <li class="nav__listitem"><a class="ttu nav__link" href="???">Our Programs</a></li>
        <li class="nav__listitem"><a class="ttu nav__link" href="???">Our Story</a></li>
      </ul>

  </koi-menu>
bresson
  • 831
  • 11
  • 20

2 Answers2

18

The use of a slot can be detected from the host element in the componentWillLoad() function:

hasLogoSlot: boolean;
hasMenuSlot: boolean;

@Element() hostElement: HTMLStencilElement;

componentWillLoad() {
    this.hasLogoSlot = !!this.hostElement.querySelector('[slot="logo"]');
    this.hasMenuSlot = !!this.hostElement.querySelector('[slot="menu"]');
}
G. Tranter
  • 16,766
  • 1
  • 48
  • 68
  • Thanks @G. Tranter, I'm going to try this. – bresson May 21 '19 at 13:17
  • 1
    @G.Tranter, it seems I was mistaken, I was experiencing some strange behavior in my app and based on a different SO post I believed the issue was this lifecycle method. I'm using Stencil 2.16. After testing with a simpler case I saw you are correct. I deleted my previous comment – Caleb Bertrand Jul 31 '22 at 19:47
6

This might not apply to your problem, but if you only want to style the slotted elements—say only add margins on non-empty slots—you can use the ::slotted pseudo-element:

::slotted([slot="logo"]) {
  /* Apply styles to non-empty logo */
}

::slotted([slot="menu"]) {
  /* Apply styles to non-empty menu */
}
Rúnar Berg
  • 4,229
  • 1
  • 22
  • 38