8

i have a requirement to call a javascript method on load of the template.

is there any way to do that in LWC?

11

Replace an init event handler in an Aura component with the standard JavaScript connectedCallback() method in a Lightning web component.

We use the init event in an Aura component to initialize a component after component construction but before rendering.

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

The doInit function in the component's controller performs any necessary initialization.

({
    doInit: function(cmp) {
        // initialize component
    }
})

In a Lightning web component, use connectedCallback() instead in the component's JavaScript file.

// mySampleInit.js
import { LightningElement } from 'lwc';
export default class MySampleInit extends LightningElement {
    connectedCallback() {
        // initialize component
    }
}

Also, read this:- Run Code When a Component Is Inserted or Removed from the DOM

  • thank you for the reply, but my requirement is to call the js method when a component is loaded. i got the answer like we can use renderedCallback() method to do the job done. thank you – sandeep ch Apr 15 at 7:22
0

To execute actions when component is rendered, use renderedCallback() method and place the required business logic inside this method.

// mySampleInit.js
import { LightningElement } from 'lwc';
export default class MySampleInit extends LightningElement {
    renderedCallback() {
        //  the required business logic to be executed when component is rendered
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.