Get child component(lightning-datatable) getSelectedRows() on parent component button event

lightning-datatablelightning-web-components

I have one parent and one reusable child component. The child component contains a data-table with check box column. The parent component has many data-table>>child components. On the button click event, I need to get each data-table selected rows. I used the below syntax on button click but always get null or error "this.template.querySelector(…).getSelectedRows is not a function"

Parent-Component

 <template>
      <div class="slds-var-m-around_medium">
        <template if:true={accountData.length}>
          <c-reusable-data-table
            data-id="overview"
            card-title="Account list"
            source-data={accountData}
            hide-checkbox="false"
            columns={accountColumns}
          ></c-reusable-data-table>
        </template>
      </div>
    </template>

Rendered HTML

enter image description here

Button click event

  handleSync() {
    debugger;
    var selectedRecords = this.template
      .querySelector("c-reusable-data-table")
      .getSelectedRows();

    console.log("selectedRecords are ", selectedRecords);

  }

How to get reusable child component selected records on the parent component button click event?

Best Answer

You need to expose on child component an api method which will contain the querySelector method and will return the selected rows to parent component.

This trailhead might be useful to you.

child

@api getRows() {
    return this.template.querySelector("lightning-datatable")
      .getSelectedRows();
}

then in your parent you can call this method on the c-reusable-data-table.

 this.template
      .querySelector("c-reusable-data-table")
      .getRows();

The reason why your solution is not working is that on the custom component there is not getSelectedRows method. This method is only on the datatable standard component.