7

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?

8

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('*')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.