LWC Check if slot is empty
Accessing assignedNodes
or assignedElements
on a <slot>
is the canonical way to verify if it has slotted content.
In the case of modal with a header, for example, the component needs to handle the case where a slotted content is added or removed. Relying on the renderedCallback
is not enough in this case since there is no guaranty for it to be invoked when the sotted content changes.
In this case, you should rely on the slotchange
event. This event fires when the slot assigned node changes in the next microtask.
You can find an example: https://playground.lwcjs.org/projects/Bt9kHN4V_/2/edit
<template>
<slot name="title"
class={slotTitleClass}
onslotchange={handleTitleSlotChange}></slot>
<slot></slot>
</template>
import { LightningElement, track } from 'lwc';
export default class Child extends LightningElement {
@track slotTitleClass = '';
handleTitleSlotChange(evt) {
const slot = evt.target;
const hasTitle = slot.assignedElements().length !== 0;
this.slotTitleClass = hasTitle ? 'with-title' : '';
}
}