Saturday 9 January 2021

 

  Component Lifecycle

Lightning web components have a lifecycle managed by the framework. The framework creates components, inserts them into the DOM, renders them, and removes them from the DOM. It also monitors components for property changes. Generally, components don’t need to call these lifecycle hooks, but it is possible.

Run Code When a Component Is Created

The constructor() method fires when a component instance is created. Don’t add attributes to the host element during construction. You can add attributes to the host element in any other lifecycle hook.

Run Code When a Component Is Inserted or Removed from the DOM

The connectedCallback() lifecycle hook fires when a component is inserted into the DOM. The disconnectedCallback() lifecycle hook fires when a component is removed from the DOM.

Run Code When a Component Renders

The renderedCallback() is unique to Lightning Web Components. Use it to perform logic after a component has finished the rendering phase.

Handle Component Errors

The errorCallback() is unique to Lightning Web Components. Implement it to create an error boundary component that captures errors in all the descendent components in its tree. It captures errors that occur in the descendant's lifecycle hooks or during an event handler declared in an HTML template. You can code the error boundary component to log stack information and render an alternative view to tell users what happened and what to do next.


  • html
<template>
    <p>Test Hook example</p>
    <lightning-card title="Life cycle hooks"  icon-name="custom:custom14">
        {msg}
    </lightning-card>
</template>


Javascript

import { LightningElement } from 'lwc';

export default class HooksExample extends LightningElement {
    msg='annappa';
    //When component is created
    constructor(){
        super();
        console.log('inside constructor');
        this.msg = this.msg+''+'PH';

    }
  //Component is inserted from DOM
    connectedCallback(){
        console.log('connected callback');

    }
    //Component is disconnected from DOM
    disconnectedCallback(){
        console.log('disconnected callback');

    }
    //Run a component when Component renders
    renderedCallback(){
        console.log('rendered callback');
    }
    //Handle component error
    errorCallback(error,stack){
        console.error('error');

    }
}

xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
       <isExposed>true</isExposed> 
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>




No comments:

Post a Comment