2

I am using the utility icons provided by slds. I want to change the fill color of the icon based on a condition.

Here is the HTML:

<template if:true={address.penetrationOnePrior}>
    <svg class={style} aria-hidden="true">
       <use xlink:href={address.penetrationTrendBefore}></use>
    </svg>
</template>

Here is the JS: I want to change the color to green if the below conditions becomes true and red if it false.

isRed = false;
@track style = DEF_STYLE;
if (penetrationOnePrior > penetrationTwoPrior) {               
   penetrationTrendBefore = "/assets/icons/utility-sprite/svg/symbols.svg#up";
   this.penetrationTrendBeforeColor();
}
penetrationTrendBeforeColor() {
   this.isRed = !this.isRed;
   this.style = `${this.isRed?'penetration-up-color':'penetration-down-color'} ${DEF_STYLE}`;
};

Here is the CSS:

.penetration-up-color {
   color: green;
}
.penetration-down-color {
   color: red;
}

1 Answer 1

3

As I said before, you can't alter the inner styles of the component. The previous solution only worked because it was in Aura. Fortunately, in LWC, you can use SVG directly, and this means we have a very simple solution. We can directly reference the SVG file and style it.

Here's a playground for you.

And here's the example source:

CSS

.red {
    fill: red;
}
.blue {
    fill: blue;
}

HTML

<template>
    <svg class={style} aria-hidden="true">
        <use xlink:href="/assets/icons/utility-sprite/svg/symbols.svg#right">
        </use>
    </svg>
    <lightning-button label="Toggle" onclick={toggleIcon}>
    </lightning-button>
</template>

JS

import { LightningElement, track, api } from 'lwc';

const DEF_STYLE = 'slds-icon slds-icon-text-default';

export default class App extends LightningElement {
    isRed = false;
    @track style = DEF_STYLE;
    connectedCallback() {
        this.toggleIcon();
    }
    toggleIcon() {
        this.isRed = !this.isRed;
        this.style = `${this.isRed?'blue':'red'} ${DEF_STYLE}`;
    }
}
4
  • Thanks @sfdcfox, tried it the first instance, didn't work for me, will have to look into it in detail tomorrow.
    – sumchans
    Mar 11, 2020 at 4:25
  • Can I ask you to look at my original post once more, I just made some changes with the sample you put in. For some reason I am not able to figure it out. As of now there is no icon shown when the code is run. Sorry for bugging again.
    – sumchans
    Mar 12, 2020 at 0:17
  • 1
    @sumchans It's fill, not color. The if() statement needs to be in a connectedCallback(), penetrationTrendBefore needs to be prefixed with this. I think that's it.
    – sfdcfox
    Mar 12, 2020 at 0:52
  • Thanks @sfdcfox, Let me try this out, will update it soon.
    – sumchans
    Mar 12, 2020 at 1:03

You must log in to answer this question.

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