[SalesForce] How to get selected row number from lightning-datatable in Salesforce LWC

I am displaying the records in the table which are to be inserted, and want to implement the delete functionality so that the user can delete the records before saving it to the database. There is no unique field or record id.

On click of a button, I want to get the selected row number from lightning-datatable. For example, if I select 3rd and 5th row in the lightning-datatable, on click of a button, I should get 3 and 5 row number.

I tried this.template.querySelector('lightning-datatable').getSelectedRows();, but I am getting complete row data.

How can I get selected row number?

Best Answer

You can not get the row numbers but you can get the selected rows. You can use getSelectedRows() method. Based on the selected rows you can find the selected records from the list of all records.

let rows = this.template.querySelector('lightning-datatable').getSelectedRows();

Or you can use the onrowselection event handler to get the selected rows.

HTML

<template>
    <lightning-datatable
            data={data}
            columns={columns}
            key-field="id"
            onrowselection={getSelectedName}>
    </lightning-datatable>
</template>

JS

getSelectedName(event) {
    const selectedRows = event.detail.selectedRows;
    // Display that fieldName of the selected rows
    for (let i = 0; i < selectedRows.length; i++){
        console.log("You selected: " + selectedRows[i].opportunityName);
    }
}

Documentation for Lwc datatable.