How to tell if slot is filled #2312
-
Hi all, first time using Lit. I'm trying to return a different HTML structure depending on if a slot has been filled, but whenever I try to query how many nodes are in the slot, it's always 0. Here's the class: // imports ...
export class Alert extends LitElement {
@property({type: String})
content: string | undefined = undefined;
@queryAssignedNodes('heading', true)
_headingNodes: NodeListOf<HTMLElement>;
render() {
return this._headingNodes.length === 0
? html`<div><slot><p>${this.content}</p></slot></div>`
: html`<section><slot name='heading'></slot><slot><p>${this.content}</p></slot></section>`
}
}
} and called like so: <wc-alert>This is some content</wc-alert>
<wc-alert><h2 slot='heading'>Alert!</h2>This is some more content</wc-alert> It seems to always have length === 0, but what I'd like is that when the 'heading' slot is filled, the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The problem you're hitting in your current implementation is that the slot you're checking with Here's a playground which includes a If possible though, I'd also suggest modifying this template so that it doesn't require switching the parent element type between If the reason you wanted to switch between Also check out WICG/webcomponents#936 for a proposal to add something like |
Beta Was this translation helpful? Give feedback.
The problem you're hitting in your current implementation is that the slot you're checking with
this._headingNodes.length
never exists, so the count of slotted children will always be 0 (because thequeryAssignedNodes
decorator defaults to 0 if the slot doesn't exist). The slot doesn't exist on first render because no child DOM exists yet on first render. And actually even if something triggered a subsequent render, the count will still always be 0, because only the default slot could have been rendered, and never theheading
slot you're looking for.Here's a playground which includes a
heading
slot even in the first case, because otherwise there is no way to check if anything was slotted…