0

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

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

5
  • 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 ? – Manish Anand Mar 27 '20 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 😀 – Abhijith E Mar 27 '20 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. – Manish Anand Mar 30 '20 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.... – Abhijith E Mar 30 '20 at 16:22
  • Ok. Will try it. – Manish Anand Mar 30 '20 at 18:27
1

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

Collection of SLDS Icon Backgrounds

Some notes:

  1. If the column is editable, then be sure to include slds-cell-edit
  2. You can use other slds data table specific classes like slds-has-error: SLDS Data Tables CSS
  3. If rows are selectable, then the hover / select will overide the cellAttributes specified background color
  4. 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

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.