1

Simple question. This won't work - It won't check my checkbox. Any solutions?

html.

<template>
   <lightning-input type="checkbox" data-id="none" label="None of the above" value="None of the above"></lightning-input>
</template>

js.

  connectedCallback() {
      let checkboxes = this.template.querySelectorAll('[data-id="none"]');
      for (let i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = true;
      }
  }

1 Answer 1

1

In connectedCallback(), the child elements haven't been rendered yet. You need to wait a tick, either by renderedCallback or by Promise.resolve:

// option 1
async connectedCallback() {
  await Promise.resolve();
  [...this.template.querySelectorAll('lightning-element')]
    .forEach((input) => { input.checked = true })
}

// Option 2
_selectedAll
renderedCallback() {
  if(this._selectedAll) {
    return;
  }
  this._selectedAll = true;
  [...this.template.querySelectorAll('lightning-element')]
    .forEach((input) => { input.checked = true })
}

You only need one of these two solutions.

4
  • Ah @sfdcfox you are always right! Yeah I totally forgot that connectedCallback() never waits it to be rendered. Thanks! this is really good example.
    – Ian Lee
    May 19, 2022 at 20:17
  • @sfdcfox how promise.resolve is interlinked with page rendering? So refreshing page is a promise that when it resolves, it runs the next lines of code in connectedcallback?
    – Pratap M
    Apr 7, 2023 at 12:41
  • @PratapM await Promise.resolve() returns control to the LWR rendering engine, and after all synchronous code (including render() and renderedCallback()) have finished, the next line of code will immediately execute. You can use this method any time you want to wait for a render cycle, not just the first. E.g. this.data = await someApexCall(); await Promise.resolve(); this.template.querySelector('something')
    – sfdcfox
    Apr 7, 2023 at 14:09
  • @sfdcfox thanks for more insights.
    – Pratap M
    Apr 8, 2023 at 6:20

You must log in to answer this question.

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