I am implementing lightning-datatable with searching but, I am facing a issue:
When i searching a new data and selected 2 - 3 by checkbox, UI only displayed last checked row only. And all other got deselected.
In other words, I search Hindi and selected any record from, then i search English, then selection of Hindi got deselected.
Is there any way, to fix this my code is below
HTML
<template>
<div class="slds-grid slds-wrap slds-m-left_xx-large">
<div class="slds-col slds-size_2-of-3 slds-m-left_xx-large">
<lightning-input class="slds-m-left_xx-large" type="search" label="Search Languages" placeholder="Filter Text" onchange={handleSearch}></lightning-input>
</div>
<div class="slds-col slds-size_2-of-3 slds-m-left_xx-large">
<div class="slds-m-left_xx-large slds-scrollable_y" style="height:15rem;">
<template if:true={data}>
<lightning-datatable hide-table-header key-field="Id" data={data} columns={columns}
onrowselection = {handleRowAction} selected-rows={listOfSelectedRecords}>
</lightning-datatable>
</template>
<template if:true={error}>
{error}>
</template>
</div>
</div>
</div>
</template>
JS
import { LightningElement, wire, track } from 'lwc';
import retrieveLocations from '@salesforce/apex/TypeAheadLWCController.retrieveLocations';
const columns = [
{ label: 'Name', fieldName: 'Name' },
];
export default class TypeAheadLWC extends LightningElement {
data;
error;
columns = columns;
searchString;
initialRecords;
listOfSelectedRecords = [];
@wire(retrieveLocations)
wiredAccount({ error, data }) {
if (data) {
console.log(data);
this.data = data;
this.initialRecords = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.data = undefined;
}
}
handleSearch(event)
{
const searchKey = event.target.value.toLowerCase();
if (searchKey)
{
this.data = this.initialRecords;
if (this.data)
{
let searchRecords = [];
for (let record of this.data)
{
let valuesArray = Object.values(record);
for (let val of valuesArray)
{
console.log('val is ' + val);
let strVal = String(val);
if (strVal && strVal.toLowerCase().includes(searchKey))
{
searchRecords.push(record);
break;
}
}
}
console.log('Matched Accounts are ' + JSON.stringify(searchRecords));
this.data = searchRecords;
}
}
else
{
this.data = this.initialRecords;
}
}
handleRowAction(event)
{
//alert('handleRowAction');
var selectedRecords = this.template.querySelector("lightning-datatable").getSelectedRows();
console.log('@@@ 1 HEY ' +JSON.stringify(selectedRecords));
if (selectedRecords)
{
for(var i=0; i<selectedRecords.length; i++)
{
if (!this.listOfSelectedRecords.includes(selectedRecords[i].Id))
{
this.listOfSelectedRecords.push(selectedRecords[i].Id);
}
}
}
console.log('@@@ 2 ' + JSON.stringify(this.listOfSelectedRecords));
}
}
I am querying Id and name from Apex.