Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something when slot does not have child nodes in lit-html

I'd like to display a text when no content is on the slot.

class List extends LitElement {
  public render() {
    return slot.length === 0 
      ? html`No content is available`
      : html`<slot></slot>`;
  }
}
like image 580
fernandopasik Avatar asked Oct 15 '25 04:10

fernandopasik


1 Answers

I think this may help :

render() {
   return html` <slot id="slot">No content is available</slot> 

`;}

firstUpdated(){
      const slot = this.shadowRoot.querySelector("#slot");
      this.slt = slot.assignedNodes();
      if (this.slt.length===0){
        console.log('No content is available')
      } else {
        console.log('Content available', this.slt)
      }
}

You can not slot's assigned nodes unless you render slot element. That's why first you need to render it. After there are a lot way to hide it. Another way is to dedect it at it's parents and pass the nr of slot element as property.

Demo

like image 145
HakanC Avatar answered Oct 19 '25 12:10

HakanC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!