Change lightning card background color depending upon field value

csslightninglightning-web-components

i want to change the background of the lightning CARD on the condition ,that when units.Available__c='NO' the card background should be red and when units.Available__c='yes' the card background should be green.
Iam new to lwc and css ,i tried many methods couldn't get much about it.
thanks in advance..

<lightning-layout>
        <div class="myColor">
        <template for:each={Unitlist.data} for:item="units"  >
            <lightning-layout-item padding="around-small" key={units} >
                
                <lightning-card key={units}  >
                    <ul>
                        <li> {units.Name},</li>
                        <li>Available: {units.Available__c} </li>
                        <div >  <lightning-button label="Quote"   onclick={handleNavigate} value={units.Id}  ></lightning-button></div>
                      </ul>
                    </lightning-card>
        
            </lightning-layout-item>
        </template>
    </div>
    </lightning-layout>
js
@wire(getUnits)Unitlist;
css
.myColor.THIS  {
    background: red;

}

Best Answer

You need to use a combination of Styling Hooks and the JavaScript map() function to achieve what you need.

First, use Styling Hooks to create 2 CSS classes - one for each state

.available{
    --sds-c-card-color-background: green;
}

.unavailable{
    --sds-c-card-color-background: red;
}

Next, edit your wire function to return a CSS class along with the unit data

unitData = [];
    
    @wire(getUnits)
    processUnits({data, error}){
        if(data){
            this.unitData = data.map(unit => {
                return {
                    ...unit,
                    cssClass: (unit.Available__c === 'YES'? 'available': 'unavailable')
                }
            });
        }
    }

Finally, use the returned cssClass property in the class attribute of lightning-card.

<template for:each={unitData} for:item="unit">
    ...
    <lightning-card class={unit.cssClass}>
        ...
    </lightning-card>
    ...
</template>