2

I have an LWC with two datatables in separate divs. The goal is for a single button in the first div to pull the selected row from both tables and pull the two IDs of the records, and to throw an error if either table doesn't have a selection. I understand using getSelectedRows to get this from one table, but is it possible to get both? Any help would be appreciated.

1 Answer 1

3

JavaScript has a number of ways to do this. Here's one example:

let eachTableSelections = [...this.template.querySelector('lightning-datatable')]
  .map(table => table.getSelectedRows());
let allTablesHaveSelections = eachTableSelections
  .every((selections) => !!selection.length);
if(allTablesHaveSelections) {
  let selectionsFromAllTables = eachTableSelections.flat();
  // Do something with this
} else {
  this.showError('At least one table has no rows selected.');
}

[...var] copies an array-like object to a real Array (so we can use .map). .map transforms the elements of one array into a new array; we use this to get the selections. .every is a method that returns true if all conditions are met, false otherwise.

!!selection.length returns true if length is not equal to 0 (at least one selection was made). .flat is a method that collapses all the nested arrays into a single flat array.

Other solutions are possible, many of which have better raw performance, but likely won't matter in your script. Imperative calls tend to be easier to read.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .