Constructor in Lightning Webcomponent


It fires when a component instance is created.
Constructor in lightning webcomponent flows from parent to child.
Lets assume that you have created two components one is child component and other one is parent component. If you have a constructor in both components then the parent constructor will be called first since the flow is from parent to child.
The first statement must be super in the constructor with no parameters.
childComponent.html
<template>
   childcomponent
</template>
childComponent.Js
import { LightningElement,api } from 'lwc';
export default class ChildComponent extends LightningElement {
	constructor(){
	super();
	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 {
	constructor(){
	super();
	console.log(Yes I am in parent component);
}
LightningApplication
<aura:application extends="force:slds">
	<c:parentComponent>
	</c:parentComponent>
</aura:application>
Output:
Yes I am in parent component.
Yes I am in child component.
Note: The flow is from parent to child so it will print parent output first and later it will print childcomponent output.
Can we define the variable in constructor?
Yes.
Can we set the value in the constructor?
Yes
Can we access the elements in the constructor?
No. when you try to do that you will get an error.
Can you load the data in the constructor?
Yes. We can do that.
Can you create a dispatch event in the constructor?
No. When you try to do that you will  get an error.
Can you create multiple constructors in the js file?
No. It wont allow you to create multiple constructors in js. If you try to do that it will display an error message.
Can we access the api property values in the constructor?
No.when you try to do that you will get the value as undefined.
import { LightningElement,api } from 'lwc';
export default class ParentComponent extends LightningElement {
	@api blogName='sfdcscenarios.blogspot.com';
	constructor(){
	super();
	console.log(public property value'+blogName);
}
}
output:
It will print undefined
What happens when you decorate the variable with track property. Will you able to access the value?
Yes. We can access the value
import { LightningElement,api } from 'lwc';
export default class ParentComponent extends LightningElement {
	@api blogName='sfdcscenarios.blogspot.com';
	constructor(){
	super();
	console.log(public property value'+blogName);
}
}
output:
sfdcscenarios.blogspot.com

Comments