0

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?

0

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++){
        alert("You selected: " + selectedRows[i].opportunityName);
    }
}

Documentation for Lwc datatable.

| improve this answer | |
  • I have used the above code. But, I don't have any unique field to compare the records and find the selected row number. Any alternate way? – Ajinkyasd Jul 13 at 8:52
  • I am displaying the records to be inserted in the table, and want to implement the delete functionality, so that user can delete the records before saving to the database. – Ajinkyasd Jul 13 at 8:54
  • If you can create a custom unique field on the data like index @Ajinkyasd – rahul gawale Jul 13 at 9:20
  • @Ajinkyasd you can check this playground I had created long back, it has delete functionality as well as the unique id generation code, search for uid. – rahul gawale Jul 13 at 11:39

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.