Sometimes, we need to show data in data table format and need to highlight specific cells based on some condition or calculations. here is how we can do with cellAttributes property.
Cell highlight in Lightning Datatable
Here we are using cellAttributes property to set custom css style class to lightning data table cell. we can use slds style class and also use our custom style classes. Here we are using slds style classes to highlight the Asian paints Ltd cell.
DataTableCellHighlight.html
<template>
<lightning-datatable
key-field="Id"
data={tableData}
columns={tableColumns}>
</lightning-datatable>
</template>
DataTableCellHighlight.js
import { LightningElement } from 'lwc';
// table columns
const COLUMNS = [
{ label: 'Id', fieldName: 'id' , type: 'integer'},
{ label: 'Name', fieldName: 'name' , type: 'string',
cellAttributes: {
class: {
fieldName: 'cellHighlightCls'
}
}},
{ label: 'Website', fieldName: 'website', type: 'url'}
];
export default class DataTableCellHighlight extends LightningElement {
tableColumns = COLUMNS;
// sample data
tableData = [
{id:101, name: 'salesforce', website:'https://www.salesforce.com', cellHighlightCls: ''},
{id:102, name: 'Asian Paints Ltd', website:'https://www.asianpaints.com/', cellHighlightCls:'slds-theme_shade slds-theme_alert-texture'},
{id:103, name: 'IndusInd Bank Ltd', website:'https://www.indusind.com/', cellHighlightCls:''}
];
}
DataTableCellHighlight.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
Also found above code in Tech Shorts Git repo