Search code examples
web-componentshadow-domstenciljs

StencilJS check if named slot is empty


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>

Solution

  • 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"]');
    }