Skip to content

Instantly share code, notes, and snippets.

@jungleeforce
Created August 17, 2019 16:12
Show Gist options
  • Save jungleeforce/7ffb0e94bf0d5641d162f6295ac9df9f to your computer and use it in GitHub Desktop.
Save jungleeforce/7ffb0e94bf0d5641d162f6295ac9df9f to your computer and use it in GitHub Desktop.
<template>
<lightning-datatable
key-field="Id"
data={results}
columns={columns}
hide-checkbox-column ="false"
show-row-number-column="true"
onsort={updateColumnSorting}
sorted-by={sortBy}
sorted-direction={sortDirection}
row-number-offset ="0" >
</lightning-datatable>
</template>
import { LightningElement,track,wire } from 'lwc';
import fetchContact from '@salesforce/apex/ContactList.fetchContactLocal';
const dataTablecolumns = [{
label: 'First Name',
fieldName: 'FirstName',
sortable : true,
type: 'text'
},
{
label : 'Last Name',
fieldName : 'LastName',
type : 'text',
sortable : true
}]
export default class ContactListLocalSort extends LightningElement {
@track results=[];
@track columns = dataTablecolumns;
@track sortBy='FirstName';
@track sortDirection='asc';
@wire(fetchContact) contactList({error, data}) {
if(data)
this.results=Object.assign([], data);
if(error)
console.log(error);
}
updateColumnSorting(event){
let fieldName = event.detail.fieldName;
let sortDirection = event.detail.sortDirection;
//assign the values
this.sortBy = fieldName;
this.sortDirection = sortDirection;
//call the custom sort method.
this.sortData(fieldName, sortDirection);
}
//This sorting logic here is very simple. This will be useful only for text or number field.
// You will need to implement custom logic for handling different types of field.
sortData(fieldName, sortDirection) {
let sortResult = Object.assign([], this.results);
this.results = sortResult.sort(function(a,b){
if(a[fieldName] < b[fieldName])
return sortDirection === 'asc' ? -1 : 1;
else if(a[fieldName] > b[fieldName])
return sortDirection === 'asc' ? 1 : -1;
else
return 0;
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment