How can we conditionally highlight/color a cell using datatable in LWC? If that's not possible , what are other options to highlight a cell conditionally in the table?
3 Answers
Yes, Conditional Formatting can be done using cellAttributes for data table
For Example, If the requirement is to format/Show all the names of users in Red whose "Due Balance" is greater than 200 and other Usernames in Green the component would be
The working example can be viewed in playground
Code would be: .HTML
<template>
<div style="height: 300px;">
<lightning-datatable
key-field="id"
data={data}
columns={columns}>
</lightning-datatable>
</div>
</template>
.JS
import {
LightningElement,
track
} from 'lwc';
const columns = [{
label: 'Label',
fieldName: 'name',
cellAttributes: {
class: {
fieldName: `format`
},
alignment: `left`
}
},
{
label: 'Phone',
fieldName: 'phone',
type: 'phone'
},
{
label: 'Balance',
fieldName: 'amount',
type: 'currency'
}
];
const recordMetadata = {
name: 'name',
email: 'email',
website: 'url',
amount: 'currency',
phone: 'phoneNumber',
closeAt: 'dateInFuture',
};
let amountOfRecords = 10;
export default class FormatTable extends LightningElement {
@track data = [];
@track columns = columns;
async connectedCallback() {
const data = await this.fetchDataHelper({
amountOfRecords
});
//Generate Dynamic Values
data.forEach(ele => {
ele.format = ele.amount > 200 ? 'slds-text-color_error' : 'slds-text-color_success';
});
this.data = data;
}
fetchDataHelper({ amountOfRecords }) {
const recordMetadata = {
name: "name",
email: "email",
website: "url",
amount: "currency",
phone: "phoneNumber",
closeAt: "dateInFuture"
};
return fetch("https://data-faker.herokuapp.com/collection", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify({
amountOfRecords,
recordMetadata
})
}).then(response => response.json());
}
}
Similarly, additional styles can be included as desired and additional icons can also be included
Additionally, more styles can be found in another example in playground
to include additional styles platform-resource-loader can be used
-
Thanks.It helps. 'Example in playground' links help. However I want to use background color (example- slds-color__background_gray-7) instead of custom icon (slds-icon-custom-custom9). Because, when I hover the cursor on a cell with slds-icon-custom , that row becomes white. I tried but couldn't find link for all the slds-color__background , can you provide link for it? Additionally , I tried adding custom css class , example - dietCSSClass : 'phoneCSSClass' in the playground example , where phoneCSSClass is in the basic.css , but cell doesn't changes. So how can we add custom css class ? Commented Mar 27, 2020 at 14:10
-
That's the last line of the answer "to include additional styles platform-resource-loader can be used" .. Please mark the answer if it solved your query 😀 Commented Mar 27, 2020 at 14:41
-
Yes, I will mark the answer. I want to use css files created for that web component in the same folder , rather than importing an external / third party css. Commented Mar 30, 2020 at 4:34
-
No, the Css would not work if included in the component.. for this the css should be stored as a static resource and exported using platform-resource-loader.... Commented Mar 30, 2020 at 16:22
-
For those looking for an easy reference of background colors / out of the box options, then as previously mentioned you can use the dynamic (row object specified) cellAttributes: { class: {fieldName: 'dataColumnOfClasses'} }
or, if fixed for the entire table column, cellAttributes: { class: 'slds-icon-* '} }
parameter when defining your columns.
I compiled the set of slds-icon-*
classes (by hue and shortest icon reference) as of 2021-04-15 and they are accessible here:
Icon Background Colors
Some notes:
- If the column is editable, then be sure to include
slds-cell-edit
- You can use other slds data table specific classes like
slds-has-error
: SLDS Data Tables CSS - If rows are selectable, then the hover / select will overide the cellAttributes specified background color
- If you want to keep / change the text color, then add a text class after the background (
slds-icon-* slds-text-color_default
): SLDS Text
I might be too late to answer the question, but recently was stuck in this situation, I used CSS selector concept to target the particular row's cell. I myslef have gone through all the posts on this thread, but could not found solution other that static resource loader.
I didn't want to use that.Hence, Here is the css code- that needs to be put in the renderedCallback section. ' (this code is making the last row's first cell of the slds-table as bold and setting pointer events as none). Here, the custom-table is the class I have given to the lightning-datatable.
<lightning-datatable
key-field="id"
data={data}
columns={columns}
class="custom-table">
</lightning-datatable>
renderedCallback(){
let style = document.createElement('style');
style.innerText = '.custom-table tr:last-child th a{font-weight: bold;color:inherit;text-decoration:none;pointer-events:none;}';
this.template.querySelector('.custom-table').appendChild(style);
}