I'm creating LWC datatables on the fly, dynamically through a REST API. If I have one table, everything I'm trying to do makes perfect sense. However, since I'm creating everything dynamically, the problems stack up. One problem I have is how to display row selections per datatable and have it be reactive. The reactive value is the the badges in the top right corners per table (see image).
Here is a link to the playground
Here is the relevant portion of the code:
app.js
column = [
{ fieldName: 'foo', label: 'Foo' },
{ fieldName: 'bar', label: 'Bar' },
{ fieldName: 'baz', label: 'Baz' },
];
data = [
{
category: 'Apples',
data: [
{ foo: "1", bar: "2", baz: "3" },
{ foo: "4", bar: "5", baz: "6" },
{ foo: "7", bar: "8", baz: "9" },
]
},
{
category: 'Oranges',
data: [
{ foo: "1", bar: "2", baz: "3" },
{ foo: "4", bar: "5", baz: "6" },
{ foo: "7", bar: "8", baz: "9" }
]
}
]
getSelections() {
let bar = {};
this.data.forEach(({ category }) => {
let selectedRows = this.template
.querySelector(`[data-id=${category}]`)
.getSelectedRows();
bar[category] = selectedRows;
});
this.foo = bar;
console.log('bar', bar);
}
app.html
<template>
<template for:each={data} for:item="table">
<div class="slds-m-bottom_large" key={table.category}>
<div class="table-header">
<h2>{table.category}</h2>
<span class="slds-badge slds-badge_inverse">
SELECTED ITEMS PER TABLE</span>
</div>
<lightning-datatable
data-id={table.category}
key-field="foo"
data={table.data}
columns={column}
onrowselection={getSelections}
>
</lightning-datatable>
</div>
</template>
</template>
This is what I'm aiming for... but generic functionality for all tables.