Search code examples
javascripthtmlcustom-element

How can a (angular) custom element tell if a <slot> is used


I have this custom element with a couple of named slots. Depending on some state, one of the slots is shown. So assume that the custom element looks like

<slot></slot>
<slot name="small"></slot>
<slot name="medium"></slot>
<slot name="large"></slot>

So, this component is used like this

<p>default</p>
<div slot="small"><p>small</p></div>
<div slot="medium"><p>medium</p></div>
<div slot="large"><p>large</p></div>

Basically if the state of the custom element is medium it will show the medium slot. But, if the medium slot is not used/defined it should show the default slot. Is something like this possible, how can I detect if a slot is used?


Solution

  • It turns out that you can check if a slot has elements. Just do

    element.shadowRoot.querySelector('slot[name=small]').assignedElements()[0];