Change button icon filling color on row action click in LWC datatable

csshtmljavascriptlightning-web-components

I have this below lwc data-table in which i have a column with slds icon. these icons are button icons which are clickable .

On the icon button click i am calling callRowAction function in which i am trying to change the icon color filing from slds-icon-text-warning to slds-icon-text-error.

after clicking i think the value is changing, but the updated color is not getting refresh on the page.

How to refresh the color on the page

enter image description here

HTML –

<template>
    <lightning-datatable key-field="id" columns={cols} data={data} onrowaction={callRowAction}>
    </lightning-datatable>
</template>

JS –

import { LightningElement, track } from "lwc";

export default class App extends LightningElement {
     @track cols = [
 
        { 
          type: 'button-icon', typeAttributes: { 
            iconName: { 
              fieldName: 'iconPriority' }, name: 'priority', iconClass: { 
                fieldName: 'iconPrioritycss' }, variant: 'bare' }, initialWidth: 30 
                },
        {
            fieldName: 'name',
            label: 'Name'
        }
    ];

     @track data = [
        {
            id: 1, name: 'Opportunity 1', iconPriority: 'utility:favorite', iconPrioritycss: 'slds-icon-text-warning'
        },
        {
            id: 2, name: 'Opportunity 2', iconPriority: 'utility:favorite', iconPrioritycss: 'slds-icon-text-warning'
        }
    ]

    callRowAction(event) {
        this.tskId = event.detail.row.Id;
        const actionName = event.detail.action.name;
        if (actionName === 'priority') {
            console.log(JSON.parse(JSON.stringify(event.detail.row)).id)
            this.changeiconcolor(JSON.parse(JSON.stringify(event.detail.row)).id);
        }
    }

    changeiconcolor(num) {
      alert(num)
      console.log(this.data[num - 1])
     this.data[num - 1].iconPrioritycss = 'slds-icon-text-error'
    }

}

Best Answer

The problem is that the framework does not know when you change the inner property of the array. So you need to reinitiate the data property.

Also, you don't need to do JSON stringify in the callRowAction just pass the row id in the other function.

Make the below changes in two functions callRowAction and changeiconcolor

callRowAction(event) {
  this.tskId = event.detail.row.Id;
  const actionName = event.detail.action.name;
  if (actionName === "priority") {
    this.changeiconcolor(event.detail.row.id);
  }
}

changeiconcolor(num) {
  this.data[num - 1].iconPrioritycss = "slds-icon-text-error";
  this.data = [...this.data]
}

Check the live playground example here

Related Topic