6

I'm trying to change the icon of a lightning button icon but the image isn't changing however I see that the attribute is being updated.

 this.template.querySelector('#'+event.target.id).setAttribute("icon-name","utility:check");
10

setAttribute is for setting HTML attributes. For component attributes, use direct assignment:

event.target.iconName='utility:check"

If you use query selectors, just remember that if it's not an HTML component, use the direct assignment method.

1
  • 1
    Interesting, I did not know that! Dec 24 '19 at 2:58
1

Using track variable is another way to go.

In the javascript controller

@track iconname = 'DefaultIconName';

handleToggleIconname(){
  this.iconname = 'NewIconName';
}

In the html template file

<lightning-icon icon-name={iconname}></lightning-icon>
1
  • 1
    +1, but note: @track is no longer necessary for shallow references, such as a string variable in your answer. You only need to track objects and arrays if you want them to be reactive.
    – sfdcfox
    Feb 14 at 0:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.