1

See this playground link for an example.

The table gets sortedBy a url, rather than label. I guess I could try to hardcode something or name my fields in a way that's easy to drop url suffix, but it's a bit dirty.

Note event.detail doesn't have a fieldLabel property, just fieldName.

Is there some more elegant solution? Feels like datatable should have built in sorting function that's controlled declaratively, but that's topic for another discussion :)

Edit: For now my fix is

const dataField = column && column.typeAttributes && column.typeAttributes.label
    && column.typeAttributes.label.fieldName || sortedBy
cloneData.sort(this.sortBy(dataField, sortDirection === 'asc' ? 1 : -1))

1 Answer 1

2

You could add a custom attribute and use that for sorting purposes:

const columns = [
    { label: 'Name', fieldName: 'name', sortBy: 'name' },
    {
        label: 'Age',
        fieldName: 'ageUrl',
        sortBy: 'age',
        typeAttributes: {
            label: {fieldName: 'age'},
        },
        type: 'url',
        sortable: true,
        cellAttributes: { alignment: 'left' },
    }
];

onHandleSort(event) {
    const { fieldName: sortedBy, sortDirection } = event.detail;
    const cloneData = [...this.data];
    const sortFieldName = this.columns.find(field=>sortedBy===field.fieldName).sortBy;
    cloneData.sort(this.sortBy(sortFieldName, sortDirection === 'asc' ? 1 : -1));
    this.data = cloneData;
    this.sortDirection = sortDirection;
    this.sortedBy = sortedBy;
}

This trades a small extra setup (sortBy) to gain the ability to sort by whatever attribute you want, even a hidden value in a completely different field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.