constructor in Lightning Web Component

Constructor() method fires when a component instance is created.

The constructor in LWC flows from parent to child which means Constructor of Parent component will get called first if you have parent child component composition.

Child Component and Controller –

childComp .html

<template>
<lightning-card title=“Child Component”>
<div class=“slds-p-left_medium slds-align_absolute-center”>
                Child Component Called
</div>
</lightning-card>
</template>
childComp.js
import { LightningElement } from ‘lwc’;
export default class childComp extends LightningElement {
    pChildList = [];
    constructor() {
        super();
        window.console.log(‘::: In Child Constructor’);
    }
    connectedCallback() {
        this.pChildList.push(‘Add Child connectedCallback’);
        window.console.log(‘::: In Child connectedCallback’);
        window.console.log(‘::: List values => ‘+ this.pChildList);
    }
}

Parent Component and Controller –

webCompLifeCycl.html

<template>
<lightning-cardtitle=“Parent Component”>
<c-child-comp></c-child-comp><br/>
<divclass=“slds-p-left_medium”>
                Page LOAD
</div>
</lightning-card>
</template>
webCompLifeCycl.js
import { LightningElement } from‘lwc’;
exportdefault class webCompLifeCycle extends LightningElement {
pList = [];
constructor() {
super();
window.console.log(‘::: In Constructor’);
    }
connectedCallback() {
this.pList.push(‘Add connectedCallback’);
window.console.log(‘::: In connectedCallback’);
window.console.log(‘::: List values => ‘+this.pList);
    }
}
Output –
LWC_Contstructor
NOTES –
  • The first statement must be super() with no parameters. This call establishes the correct prototype chain and value for this. Always call super() before touching this.
  • Don’t use a return statement inside the constructor body, unless it is a simple early-return (return or return this).
  • Don’t inspect the element’s attributes and children, because they don’t exist yet.
  • Don’t inspect the element’s public properties, because they’re set after the component is created.

One Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s