0

I have a parent lwc component and child lwc component.I need for each item in dataList display child component and then call method for each child component. How can I do it via lwc? Its easier via aura with dynamic component creation. And alert(childElements.length) displays 0 on first apiParentMethod, but display some number on each future call. I need to rerender it or change the logic somehow.

Actually I dont need an dataList property and using it just for loop.

parent.js

   @api apiParentMethod(dataList) {
       apiParentMethod.forEach(data=> this.parentMethod(data,data.type));
   }

   parentMethod( data, type) {

       let dataObject= {
          type:type,
          data:data
       }
       this.dataList.push(dataObject);
       this.dataList= [...this.dataList];
       let childElements = this.template.querySelectorAll('c-child');
       alert(childElements.length);  
    }
 }

parent.html

<template>
    <template for:each={customToasts} for:item="customToast">
        <c-child key ={data.list} for:item="data"/>
    </template>
</template>

child.js

@api childMethod(data,type) {
    alert(data);
    alert(type);
}

2 Answers 2

0

You can wait for a render cycle asynchronously:

   async parentMethod( data, type) {
       let dataObject= {
          type:type,
          data:data
       }
       this.dataList.push(dataObject);
       this.dataList= [...this.dataList];
       await Promise.resolve(); // wait for a render cycle
       let childElements = this.template.querySelectorAll('c-child');
       alert(childElements.length);  
    }
0

You can use renderedCallback()

doc - https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.create_lifecycle_hooks_rendered

parent.js

renderedCallback() {
    console.log(this.template.querySelectorAll('c-child').length);
}

Thanks

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .