4

What I understand from documentation is that we cannot access child component elements inside connectedcallback because they're not yet created - that means they don't exist yet. However, we can access the elements from the host component/ component in which connectedcallback resides. I tried using queryselector in all connectedcallback, renderedcallback and disconnectedcallback and end up getting null value everywhere. No sure what's wrong.

HTML

<template>
    <lightning-card title ="LifeCycle Hooks!!">
        <div>
            <p data-id={sMessage}>{sMessage}</p>
        </div>
    </lightning-card>
</template>

JS

connectedCallback(){
        console.log('This is connectedcallback');
        console.log('Query Selector : ' ,this.template.querySelector('p'));
        console.log('Query Selector this: ' ,this.querySelector('p'));
        console.log('Greeting connectedcallback: ',this.sGreeting)
        this.sGreeting+='??';
        console.log('Updated Greeting connectedcallback! : ',this.sGreeting)
    }

enter image description here

This is how console looks. Can someone please help me understand what I'm missing here?

1
  • Have a read of my observation about connectedCallback() here Apr 21, 2020 at 3:35

3 Answers 3

2

The "host" refers only to the top-level template. Everything within is a "child" element. None of them are available until after render() is called. In your example, p is a child of div, which is a child of lightning-card, which itself is a child of template. If you want to do anything with p, you need to wait until later.

1

From the lwc documentation it is clear that

You can’t access child elements in the component body because they don’t exist yet. You can access the host element with this.template. In your example host is the template

Hence to access the child component you will need to use renderedCallback.

The below should work

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {

   connectedCallback(){
    console.log('This is connectedcallback');
    console.log('Query Selector : ' ,this.template.querySelector('p'));
  }

 renderedCallback() {
    console.log('This is renderedcallback');
    console.log('Query Selector : ' ,this.template.querySelector('p'));
 }
}

From the documentation

Use renderedCallback() to understand the state of the "inside" world (a component's UI and property state), and use connectedCallback() to understand the state of the "outside" world (a component's containing environment).

0

Try calling in renderedCallback() to perform logic after a component has finished the rendering phase. Refer to doc

You must log in to answer this question.

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