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('*')
3
  • 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() Commented Mar 16, 2023 at 16:24
  • 1
    Thanks @MatthewSouther for posting this. It's the sort of thing that can waste lots of time...
    – Keith C
    Commented Mar 16, 2023 at 20:21
  • 1
    Coming back to this thread once again. It would appear that something changed in the past year -- or else I was confused a year ago, which is very possible. It now appears that this.template.querySelector()/this.template.querySelectorAll() DO NOT work in the case of dragged and dropped slot elements in LWR sites, and this.querySelector()/this.querySelectorAll() DO work, per @Keith C's answer. Which is comforting, although I just wasted a bunch of time figuring that out. Commented May 21 at 20:29

You must log in to answer this question.

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