+ Start a Discussion
Nikhil TakawaleNikhil Takawale 

How to apply style based on condition in lwc?

Hi,
I have one use case where We want to update the lightning web component to show the "Lowest Cost" column in red if the lowest cost is lower than the Unit cost.


User-added image
Welcome to your suggestions.

Thanks
Nikhil
Nayana KNayana K
You need a extra variable in wrapper. Sadly, lwc doesn't give flexibility to arithmentic operators in html (unlike Aura comp).
Let's day records variable holding the list of records. Then,
@track recordsWrap = [];

.....................

var isLess;
var styleColor;
records.forEach(recordI => {
	isLess = recordI.Lowest_Cost__c < recordI.unit_Cost__c;
	styleColor = isLess ? 'background-color:red' : 'backrgound-color:none';
	recordsWrap.push({"styleColor" : styleColor, "record" : recordI});
})

html:
<template for:each={recordsWrap} for:item="recI" for:index="index">
	<tr key={recI.record.Id}>
		<td class={recI.styleColor}>
			{recI.record.Lowest_Cost__c}
		</td>
	</tr>
</template>

​​​​​​​

 
Nayana KNayana K
<template for:each={recordsWrap} for:item="recI" for:index="index">
	<tr key={recI.record.Id}>
		<td style={recI.styleColor}>
			{recI.record.Lowest_Cost__c}
		</td>
	</tr>
</template>

Sorry, it was a type. td should have style not class in this example.
Ertyq MrskErtyq Mrsk
@NayanaK

I was able to see your answer as it is same with my requirement.

I tried to replicate your suggestion, but background color does not change based on condition. Can you also check my code?

html file
<!-- body section in html-->
<tbody>
<template if:true={actualResults}>
    <template for:each={actualResults} for:item="keyValue">
        <tr key={keyValue.key}>
            <td scope="col" style={keyValue.styleColor}>
                <div>{keyValue.value.computedValue}</div>
            </td>
        </tr>   
    </template> 
</template>
</tbody>

javascript file
import getAllResult from '@salesforce/apex/SampleController.getAllResult';

export default class SampleLWC extends LightningElement {

@track actualResults = [];

//section in javascript

getAllResult()
    .then(result => {
        if (result) {
            let mapResult = [];
            
            var styleColor;    

            for (var key in result) {
                mapResult.push({ key: key, value: result[key] });
                        
            }
            this.actualResults = mapResult.map(e => {
                 let isLess = e.Computed_Value__c < 1000;
                 e.styleColor = isLess ? 'background-color:red' :'background- 
                 color:none';
                 return e;
            });
        }
    })
    .catch(error => {
        this.error = error;
    });
}
Thanks!
Nayana KNayana K
Hi Ertyz,

Can you print this.actualResults using console.log as last statement in try block. Paste the data here. It will help me understand how the actualResult variable data is framed.
Ertyq MrskErtyq Mrsk
It returns the following 'Object'.

This is the screenshot when I expand it when inspecting the source in chrome.

User-added image
Ertyq MrskErtyq Mrsk
My aim is be able to format the background color of the result of map collection which is `mapResult`. I am not really sure how to proceed.
Nayana KNayana K
I understood the requirement. But, I just want to see how the data is framed.
CAn you please paste SampleController.getAllResult apex code once
Nayana KNayana K
import getAllResult from '@salesforce/apex/SampleController.getAllResult';

export default class SampleLWC extends LightningElement {

@track actualResults = [];

//section in javascript

getAllResult()
    .then(result => {
        if (result) {
            let mapResult = [];
            
            var styleColor;    

            for (var key in result) {
                mapResult.push({ key: key, value: result[key] });
                        
            }
            this.actualResults = mapResult.map(e => {
                 let isLess = e.Computed_Value__c < 1000;
                 e.styleColor = isLess ? 'background-color:red' :'background- 
                 color:none';
                 return e;
            });
           console.log('==data==', this.actualResults);
           
        }
    })
    .catch(error => {
        this.error = error;
    });
}

Please replace this js file and open chrome console and look for ==data== in the console
 
Ertyq MrskErtyq Mrsk
Update: I transferred the styling from <td> to <div>, and ==data== is returned. 
 
<td scope="col">
       <div  style="keyValue.styleColor">{keyValue.value.computedValue}</div>
</td>

Result:

User-added image

Is this the result you are looking for? Not sure if this helps...
Nayana KNayana K
Yes If you expand that variable output that Handler or Target..somewhere you will see the data..

Also, try below code once
<tr key={keyValue.key}>
            <td scope="col" style={keyValue.value.styleColor}>
                <div>{keyValue.value.computedValue}</div>
            </td>
        </tr>


 
Ertyq MrskErtyq Mrsk
Modified again the html to the following:
 
<tr key={keyValue.key}>
      <td scope="col" style={keyValue.value.styleColor}>
            <div>{keyValue.value.computedValue}</div>
       </td>
</tr>

This is the current result:

User-added image

Tried expanding each item, and I can see record data, but can't include here as it already contains some confidential details.

But I checked that some records have less than 100 value so I am expecting the background color to be red. But the console displays otherwise.
Nayana KNayana K
Now I understood the pattern of your data (no need to  expand further).

Change the code back to 
<tr key={keyValue.key}>
      <td scope="col" style={keyValue.styleColor}>
            <div>{keyValue.value.computedValue}</div>
       </td>
</tr>

Notice there are only 6 records returned and all are having background color none..
Try below code:
let isLess = e.value.Computed_Value__c < 1000;
                 e.styleColor = isLess ? 'background-color:red' :'background- 
                 color:none';

Or
let isLess = e.value.computedValue < 1000;
                 e.styleColor = isLess ? 'background-color:red' :'background- 
                 color:none';
Basically, you are missing right variable in isLess condition I guess..Please double check

 
Ertyq MrskErtyq Mrsk
Hi @NayanaK

You are great! It is finally working now :) Updating codes to following:

html file:
<!-- body section in html-->
<tbody>
<template if:true={actualResults}>
    <template for:each={actualResults} for:item="keyValue">
        <tr key={keyValue.key}>
            <td scope="col" style={keyValue.styleColor}>
                <div>{keyValue.value.computedValue}</div>
            </td>
        </tr>   
    </template> 
</template>
</tbody>

javascript file:
 
import getAllResult from '@salesforce/apex/SampleController.getAllResult';

export default class SampleLWC extends LightningElement {

@track actualResults = [];

//section in javascript

getAllResult()
    .then(result => {
        if (result) {
            let mapResult = [];
            
            var styleColor;    

            for (var key in result) {
                mapResult.push({ key: key, value: result[key] });
                        
            }
            this.actualResults = mapResult.map(e => {
                 let isLess = e.value.computedValue < 1000;
                 e.styleColor = isLess ? 'background-color:red' :'background-color:none';
                 return e;
            });
        }
    })
    .catch(error => {
        this.error = error;
    });
}

The variable works instead of the actual API name.

Again, thank you very much for your help and effort in guiding me through it. Really appreciated it :) 

Cheers!
Nayana KNayana K
Glad that it worked :)
Cheers!
Mosh HamedaniMosh Hamedani
Our  web scraping Service (https://it-s.com/our-services/data-tranformation-services/web-scraping-services/) provides high-quality structured data to improve business outcomes and enable intelligent decision making,
Our Web scraping service allows you to scrape data from any websites and transfer web pages into an easy-to-use format such as Excel, CSV, JSON, and many others