bresson
bresson

Reputation: 901

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>

Upvotes: 6

Views: 6766

Answers (2)

R&#250;nar Berg
R&#250;nar Berg

Reputation: 4842

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 */
}

Upvotes: 7

G. Tranter
G. Tranter

Reputation: 17938

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

Upvotes: 18

Related Questions