Sub topic 8
Selecting rows
This chapter covers how lightning-datatable handles row selection. You will read the selected rows, preselect rows, limit selection to one row, and avoid the common mistakes. It assumes you can already render a table with data, columns, and a key-field, and that you know how to bind event handlers in an LWC template.
How selection works
By default, lightning-datatable adds a checkbox column on the left. Each row has a checkbox, and the header has a "select all" checkbox. Selection is tracked by the table using the key-field value of each row. That is why key-field must be unique: two rows with the same key would be selected together.
Earlier chapters used hide-checkbox-column to remove the checkboxes. Selection is on whenever that attribute is absent. Whenever the selection changes, the table fires a rowselection event.
The event detail contains selectedRows, an array of the full row objects that are now selected. It does not hold only the changes. Each event gives you the whole current selection.
Reading the selected rows
Add an onrowselection handler in the template and store the array in the component.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
onrowselection={handleRowSelection}>
</lightning-datatable>
<p class="slds-p-around_small">Selected: {selectedCount}</p>
</lightning-card>
</template>import { LightningElement } from 'lwc';
export default class ContactTable extends LightningElement {
columns = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'email' }
];
data = [];
selectedRows = [];
handleRowSelection(event) {
this.selectedRows = event.detail.selectedRows;
}
get selectedCount() {
return this.selectedRows.length;
}
}The objects in selectedRows are the row objects from data, so they carry every field you loaded, not only the displayed columns. For a button such as "Email selected contacts", map the array to what you need:
get selectedIds() {
return this.selectedRows.map((row) => row.Id);
}You can also read the selection on demand without storing it. The table exposes getSelectedRows(), which returns the same array of row objects. Get a reference with this.template.querySelector('lightning-datatable').
handleEmailClick() {
const table = this.template.querySelector('lightning-datatable');
const rows = table.getSelectedRows();
console.log(`Emailing ${rows.length} contacts`);
}Use the event when the UI reacts to the selection, for example enabling a button. Use getSelectedRows() when you only need the value at the moment of a click.
Preselecting rows with selected-rows
The selected-rows attribute takes an array of key-field values, not row objects. Binding it lets the component set or restore a selection.
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
selected-rows={selectedIds}
onrowselection={handleRowSelection}>
</lightning-datatable>selectedIds = [];
handleRowSelection(event) {
this.selectedIds = event.detail.selectedRows.map((row) => row.Id);
}
selectFirstTwo() {
this.selectedIds = this.data.slice(0, 2).map((row) => row.Id);
}Here the component keeps the selection as an array of ids, which is what the attribute needs. Updating selectedIds updates the checkboxes. Notice the distinction:
| Item | Contains | Direction |
|---|---|---|
| `event.detail.selectedRows` | Full row objects | Table to component |
| `selected-rows` attribute | Key-field values (strings) | Component to table |
| `getSelectedRows()` | Full row objects | Table to component |
Programmatically changing selected-rows does not fire rowselection. Update any dependent state yourself when you set the ids.
Single-row selection
To make the table behave like radio buttons, set max-row-selection="1". The checkboxes become radio buttons and the "select all" control disappears.
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
max-row-selection="1"
onrowselection={handleRowSelection}>
</lightning-datatable>Any number works. With max-row-selection="3", once three rows are selected, the other checkboxes are disabled until the user clears one. The header "select all" checkbox is hidden whenever the limit is set, because it could exceed the limit.
When a limit is set, selected-rows should not hold more ids than the limit. Preselecting more than the limit leads to inconsistent behavior, so trim the array first.
If you want a table with no selection at all, use hide-checkbox-column as before. If you want a radio-style selection with no visible control column, that is not provided. The table always shows the selection column unless you hide it, and then users cannot select rows by clicking.
Keeping selection when data changes
Selection is keyed by key-field. This has useful and surprising effects.
- If you replace
dataafter a sort, rows with the same ids stay selected, provided you also keep them inselected-rows. When you do not bindselected-rows, the table keeps its own internal selection, which is normally preserved across a re-sort. - If you reload data from Apex and some previously selected ids are gone, those rows are no longer in the table. Your stored
selectedRowsarray may still contain stale objects. Filter it against the new data. - If you refresh with
refreshApex, the row objects are new copies. Selected row objects you stored earlier are now outdated, for example if a field was edited. Store ids and look the rows up again when you need fresh values.
get selectedRecords() {
const ids = new Set(this.selectedIds);
return this.data.filter((row) => ids.has(row.Id));
}This getter always returns current objects for the selected ids. It also drops ids that are no longer in data.
Common errors
- Passing row objects to
selected-rows. The attribute expects ids. Passing objects selects nothing and gives no error. - Duplicate or missing key-field values. Rows with the same key appear selected together. Check that the field named in
key-fieldis in your SOQLSELECTlist. - Mutating the selected array.
selectedRowscomes from the event. Treat it as read-only and copy it before you sort or splice it. - Expecting
rowselectionafter a programmatic change. It does not fire. Update dependent state in the same method that setsselected-rows. - Select all with large lists. "Select all" selects only the rows currently loaded in
data, not every record in the object. With infinite loading, it covers only the rows loaded so far. - Assuming selection survives a page reload. The table keeps it only in memory. Persist it yourself if you need it.
Putting it together: bulk action button
This version stores ids, enables a button only when rows are selected, and reads fresh records when the button is clicked.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<lightning-button
slot="actions"
label="Process selected"
disabled={noSelection}
onclick={handleProcess}>
</lightning-button>
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
selected-rows={selectedIds}
onrowselection={handleRowSelection}>
</lightning-datatable>
</lightning-card>
</template>import { LightningElement } from 'lwc';
export default class ContactBulk extends LightningElement {
columns = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'email' }
];
data = [];
selectedIds = [];
handleRowSelection(event) {
this.selectedIds = event.detail.selectedRows.map((row) => row.Id);
}
get noSelection() {
return this.selectedIds.length === 0;
}
handleProcess() {
const ids = [...this.selectedIds];
console.log('Processing', ids);
}
}The slot="actions" places the button in the card header. The data array is empty here for brevity. In a real component, wire it as shown in the loading chapter.
Exercise
A user selects three contacts. Your component stores event.detail.selectedRows and also binds selected-rows={selectedRows} to the same array. The table shows no checkboxes as selected after the next render. What is wrong, and how do you fix it?
Show answer
selected-rows expects an array of key-field values (here, contact Ids), but selectedRows holds full row objects, so no row matches. Store ids instead: this.selectedIds = event.detail.selectedRows.map((row) => row.Id); and bind selected-rows={selectedIds}.
Exercise
How do you let users pick exactly one row, and what happens to the "select all" checkbox when you do?
Show answer
Set max-row-selection="1" on lightning-datatable. The checkboxes become radio buttons and the "select all" control is hidden.
Exercise
You call refreshApex after an inline edit. Why is it safer to keep selected ids than the selected row objects?
Show answer
refreshApex returns new row objects, so stored objects can hold outdated field values. Ids stay valid, and you can filter the refreshed data by id to get current rows.