Skip to main content

Hi In Aura component a child component can expect the Parent method name in 

<aura:attribute name="method" type="Aura.action">

and then can call the parent method from child component using 

var action = component.get("v.method");

$A.enqueueAction(action);

I am trying to do the same but in LWC. I know I can easily achieve child-to-parent communication using events but I wanted to do it the same way as we do in the aura. was trying to search for some reference but didn't find any ref. if anyone knows how we can call the parent component method directly from child comp please let me know 

 

#LWC  #Lightning Web Components

4 respostas
  1. 6 de ago. de 2021, 14:11

    @Kishan Kumar

    -Case1: the method you want to pass in parameter doesn't use some of the parent attributes

    You don't need to care about the context

     

    ----PARENT----

    export default class parent extends LightningElement {

        methodParent(){

            return 1+2

        }

    }

     

    <template>

        <c-child method={methodParent}></c-child>

    </template>

     

    ----CHILD----

    export default class child extends LightningElement {

        

        @api method;

     

        callParentMethod(){

            this.method()

        }

    }

     

    -Case2:the method you want to pass in parameter uses some of the parent attributes

    You need to care about the context

     

    ----PARENT----

    export default class parent extends LightningElement {

        attribute1;

        attribute2;

        methodParent(){

            return this.attribute1+this.attribute2

        }

     

        //the bind method is used to bind the parent context to the method methodParent

        //so that calling methodParentBindedWithTheContext to the attribute method of the child on the template, it will return the 'methodParent' binded with the parent context 

        methodParentBindedWithTheContext(){

            return this.methodParent.bind(this)

        }

    }

     

    <template>

        <c-child method={methodParentBindedWithTheContext}></c-child>

    </template>

     

    ----CHILD----

    export default class child extends LightningElement {

        

        @api method;

     

        callParentMethod(){

            // method is then executed with the context of parent(it still have access to the parent properties because of the binding done)

            this.method()

        }

    }

0/9000