[SalesForce] Get data from embedded LWC datatable to save

I have a for loop that calls another lwc that generates a lightning-datatable:

</template>
<template for:each={iterateOnCerts} for:item="cert" for:index="index">
    <div key={cert}>
        <c-<child lwc name> sample-number={value} in-number={cert}></c-<child lwc name>>
    </div>
</template>

<lightning-button variant="outline" label="Save" title="Save" onclick={save}></lightning-button>

javascript funtion:

save(event) {
    var row = event.detail.row;
    alert(row.Id);
    //call controller to save
    ...
}

Called lwc:

<template>
    <lightning-datatable
        key-field="id"
        data={data}
        columns={columns}
        hide-checkbox-column
        hide-row-number-column
        onrowaction={handleRowAction}
        suppress-bottom-bar>
    </lightning-datatable>
    <lightning-button variant="outline" label="Add Row" title="Add Row" onclick={handleAddRow}></lightning-button>
</template>

Here is a screenshot of how it looks:

enter image description here

The fields on the table are set to editable: true

There could be multiple tables generated from the for loop.

Each table represents a parent sObject and each row a child sObject.

I need to be able to get the data from the tables via the save button on the parent page.

Any help on this is greatly appreciated

Best Answer

        <lightning-datatable 
            key-field="Id"
            data={data}
            columns={columns}
            hide-checkbox-column
            onrowaction={handleRowAction}
            **data-id={tableId}**
            suppress-bottom-bar>
        </lightning-datatable>

In the child, I can then get the table I want as the data-id is the text table with a counter appended (counter passed in html loop).

@api
getTableData() { //called from parent
    let dataTable = this.template.querySelector(`[data-id="table${this.inNumber}"]`);
    return dataTable.draftValues;
}

and finally in the parent I call getTableData

save() {
    this.inLineItems = [];
    let tableComponents = this.template.querySelectorAll('c-<child lwc name>');
    for (const aTable of tableComponents) {
        let rowData = aTable.getTableData();
        this.inLineItems = this.inLineItems.concat(rowData);
    }
    console.log(`in Line Items: ${JSON.stringify(this.inLineItems)}`);
}