Search code examples
lit-elementlit-html

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>`;
  }
}

Solution

  • 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