1

Can we change the cell text color based on value? for example: if a cell value is "Active" then make the color green, if not then make it red.

enter image description here

I have checked cellAttribute for lightning:datatable documentation, but it's not helpful.

2

1 Answer 1

4

I think you can achieve it using the cellAttribute. Here is an example where I tried to explain it to you. It might not be a perfect solution but it can serve your purpose.

JSController code

({
init: function (cmp, event, helper) {
    cmp.set('v.mycolumns', [
        { label: 'Opportunity name', fieldName: 'opportunityName', type: 'text'},
        {
            label: 'Confidence',
            fieldName: 'confidence',
            type: 'percent',
            cellAttributes: { class: { fieldName: 'status' } }
        },
        {
            label: 'Amount',
            fieldName: 'amount',
            type: 'currency',
            typeAttributes: { currencyCode: 'EUR'}, cellAttributes: { alignment: 'right' }
        },
        { label: 'Contact Email', fieldName: 'contact', type: 'email'},
        { label: 'Contact Phone', fieldName: 'phone', type: 'phone'}
    ]);

        cmp.set('v.mydata', [{
                id: 'a',
                opportunityName: 'Cloudhub',
                confidence: 0.2,
                status: 'Active',
                amount: 25000,
                contact: '[email protected]',
                phone: '2352235235',
                trendIcon: 'utility:down'
            },
            {
                id: 'b',
                opportunityName: 'Quip',
                confidence: 0.78,
                    status: 'Inactive',
                amount: 740000,
                contact: '[email protected]',
                phone: '2352235235',
                trendIcon: 'utility:up'
        }]);
   },
   getSelectedName: function (cmp, event) {
       var selectedRows = event.getParam('selectedRows');
       // Display that fieldName of the selected rows
       for (var i = 0; i < selectedRows.length; i++){
           alert("You selected: " + selectedRows[i].opportunityName);
       }
   }
})

Style

.THIS .Active {
   background-color: green;    
}
.THIS .Inactive {
   background-color: red;    
}

We are using the cellAttribute and where we have assigned the class dynamically to the cell. We have declared the css in the style with the same field values. Here status will have 2 values and those are declared as CSS properties.

cellAttributes: { class: { fieldName: 'status' } }

I hope it will help.

Not the answer you're looking for? Browse other questions tagged .