connectedCallback in Lightning Webcomponent


It is called when the component is inserted into the dom.
The flow is from parent to child.
It will be fired more than once.
childComponent.html
<template>
   childcomponent
</template>
childComponent.Js
import { LightningElement } from 'lwc';
export default class ChildComponent extends LightningElement {
	connectedCallback(){
	console.log(Yes I am in child component);
}
parentComponent.html
<template>
<c-child-Component/>
</template>
parentComponent.js
import { LightningElement,api } from 'lwc';
export default class ParentComponent extends LightningElement {
   connectedCallback(){
   console.log(Yes I am in parent component);
   }
}
Output:
Yes I am  in parent component.
Yes I am in child component.
Can we create multiple connected call backs in js?
Yes.
Does it throw any error if you create multiple connected callback methods in Js?
No.
Can we access the elements in the connectedCallback?
No. when you try to do that you will get an error.
parentComponent.html
<template>
    <lightning-input type="text" label="BlogName" value={blogName} class="blgName">
    </lightning-input>
</template>
ParentComponent.Js
import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
    blogName='sfdcscenarios.blogspot.com';
    connectedCallback(){
        console.log('value'+this.template.querySelector(".blgName").value);
    }
}
output:
Error
Can you load the data in the connectedCallback?
Yes. We can do that.
Can you create a dispatch event in the connectedCallback?
Yes.
Can you override the values in the connectedCallback?
Yes.
Example:
import { LightningElement,api } from 'lwc';
export default class ParentComponent extends LightningElement {
   connectedCallback(){
   @api name;
   connectedCallback(){
       this.name='brahmanaidu';
       console.log('first connected call back'+this.name);
   }
   connectedCallback(){
    this.name='Mandalapu Brahmanaidu';
    console.log('first second call back'+this.name);
   }
}
Output:
Mandalapu Brahmanaidu.
Since we have written  multiple connectedcallbacks so the last one will get executed and it will override the values.
Can we load the data in connectedCallback?
Yes.
Can we set the properties in connectedCallback?
Yes.
Can we dispatch the custom event in connectedCallback?
Yes.

Comments