0

This question already has an answer here:

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.

marked as duplicate by Raul, Pranay Jaiswal, battery.cord, Himanshu, Martin Lezer Jan 2 at 9:50

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

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: 'jrogers@cloudhub.com',
                phone: '2352235235',
                trendIcon: 'utility:down'
            },
            {
                id: 'b',
                opportunityName: 'Quip',
                confidence: 0.78,
                    status: 'Inactive',
                amount: 740000,
                contact: 'quipy@quip.com',
                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 or ask your own question.