Can anyone tell me how do I create multiple data table using single lightning data table in my html and iterating over with template for each with the list ?
I am looking at something like this:
Please note all the information of table 1 and table 2 including columns,data values is in a JSON that I would receiving via apex.
I tried with this but looks like I am missing something here are the JS and HTML files:
import { LightningElement } from 'lwc';
const everythingData = [];
const alldata = [];
const data1 = [
{ id: 1, name: 'Billy Simonns', age: 40, email: '[email protected]' }];
const data2 = [
{ id: 2, name: 'Kelsey Denesik', age: 35, email: '[email protected]' }
];
alldata.push(data1);
alldata.push(data2);
const allColumns = [];
const columns = [
{ label: 'Name', fieldName: 'name' },
{
label: 'Age',
fieldName: 'age',
type: 'number',
sortable: true,
cellAttributes: { alignment: 'left' },
},
{ label: 'Email', fieldName: 'email', type: 'email' },
];
const columns1 = [
{ label: 'Name', fieldName: 'name' },
{
label: 'Age',
fieldName: 'age',
type: 'number',
sortable: true,
cellAttributes: { alignment: 'left' },
},
{ label: 'Email', fieldName: 'email', type: 'email' },
];
allColumns.push(columns);
allColumns.push(columns1);
everythingData.push(allColumns);
everythingData.push(alldata);
export default class DemoApp extends LightningElement {
alldata = alldata;
allColumns = allColumns;
everythingData = everythingData;
defaultSortDirection = 'asc';
sortDirection = 'asc';
sortedBy;
// Used to sort the 'Age' column
sortBy(field, reverse, primer) {
const key = primer
? function (x) {
return primer(x[field]);
}
: function (x) {
return x[field];
};
return function (a, b) {
a = key(a);
b = key(b);
return reverse * ((a > b) - (b > a));
};
}
onHandleSort(event) {
const { fieldName: sortedBy, sortDirection } = event.detail;
const cloneData = [...this.data];
cloneData.sort(this.sortBy(sortedBy, sortDirection === 'asc' ? 1 : -1));
this.data = cloneData;
this.sortDirection = sortDirection;
this.sortedBy = sortedBy;
}
}
HTML:
<template>
<template for:each={everythingData.allColumns} for:item="acc">
<template for:each={everythingData.alldata} for:item="def">
<lightning-datatable
key-field={acc.def.id}
columns={acc}
data={def}
hide-checkbox-column
default-sort-direction={defaultSortDirection}
sorted-direction={sortDirection}
sorted-by={sortedBy}
onsort={onHandleSort}>
</lightning-datatable>
</template>
</template>
</template>
