10

I have an LWC that wraps other child LWCs via a slot:

<template>
    ...
    <div class="sections-content-container">
        ...
        <slot></slot>
        ...

and would like to execute a method on each child LWC, guarded by a duck typing check typeof child.save === "function". But when I this.template.querySelector('slot') the child LWCs are not available.

(This is a variation of Call Methods on Child Components where no slots are used.)

Is there a pattern that can accomplish this, short of broadcasting a LMS message?

1 Answer 1

12

Found it in the docs in "Access Elements Passed Via Slots" of the Pass Markup into Slots page:

However, the DOM elements that are passed into the slot aren’t part of the component’s shadow tree. To access elements passed via slots, a component calls this.querySelector() and this.querySelectorAll().

compared to the normal this.template.querySelector() and this.template.querySelectorAll().

With this, I can invoke the methods.

PS

For my case where I want to match any immediate child elements of the slot this selector works well:

this.querySelectorAll('*')
2
  • 2
    An undocumented exception to this rule is elements dragged and dropped into slots in LWR sites using Experience Builder (see developer.salesforce.com/docs/atlas.en-us.exp_cloud_lwr.meta/…). To access these elements, apparently we have to use this.template.querySelector()/this.template.querySelectorAll() Mar 16 at 16:24
  • 1
    Thanks @MatthewSouther for posting this. It's the sort of thing that can waste lots of time...
    – Keith C
    Mar 16 at 20:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .