I have created multiple instances of child component in parent component using iteration.

<template for:each={vohmObjectList} for:item="vohmobject" for:index="index">
  <div key={vohmobject.fields.Id}>
      ondeleted = {handleVOHMDelete}

There is a public method in child component which returns all the data present there.

getVOHMObject() {
    const vohmObjectInput = {};
    vohmObjectInput[TYPE_FIELD.fieldApiName] = this.vohmTypeField;
    vohmObjectInput[DISPLAY_NAME_FIELD.fieldApiName] = this.vohmDisplayNameField;
    vohmObjectInput[STAND_FIELD.fieldApiName] = this.vohmStandField;
    vohmObjectInput[LENGTH_FIELD.fieldApiName] = this.vohmLengthField;
    vohmObjectInput[WIDTH_FIELD.fieldApiName] = this.vohmWidthField;
    vohmObjectInput[HEIGHT_FIELD.fieldApiName] = this.vohmHeightField;
    vohmObjectInput[WEIGHT_FIELD.fieldApiName] = this.vohmWeightField;
    vohmObjectInput[HMV_FORM_FIELD.fieldApiName] = this.vohmHMVFormField;
    vohmObjectInput[VOHM_ID_FIELD.fieldApiName] = this.vohmObjectId;

    return vohmObjectInput;

I want to call this method for all the child components and put returned data in a list (so that I can update these records by calling apex method).

I tried using querySelector thinking that it would return a list of all child component instances, but it only returns first instance.

const objectsToUpdate = this.template.querySelector('c-vehicle-or-heavy-machine');

Is there any way to call @api method for all child components?

  • 2
    querySelectorAll ? – glls Jul 21 '19 at 19:12

I tried using querySelector thinking that it would return a list of all child component instances, but it only return first instance.

you can use querySelectorAll if you want to fetch all of the them and not just the first.

@track childComponentsDataList = [];
    connectedCallback() {
        this.childComponents = this.template.querySelectorAll('c-vehicle-or-heavy-machine');
        this.childComponentsDataList = this.childComponents.map(comp=>comp.getVOHMObject());

Note: Do not use forEach function or for loop as it will have performance issues because you will have to keep adding to same array (by using push). Instead when you use map function, it create new array instance and return it - this is best practice as per defined by many other libraries like angular and react and even LWC.

  • Thank you for your valuable insight. this.template.querySelectorAll was returning HTML Collection, I had to covert it to Array before using map function on it. – Abhishek Prakash Jul 22 '19 at 9:06

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.