0

When I click on one of these actions, I want to change the color of the selected button: enter image description here

JS:

import { LightningElement } from 'lwc';
export default class Demo extends LightningElement {

columns=[];
recordsDisplayed = [{"Id":'111',"Name":"name1","Phone":"01234567"}, {"Id":'222',"Name":"name2","Phone":"4567890"}];

connectedCallback() {
    this.columns = [
        { label: 'Name', fieldName: 'Name'},
        { label: 'Phone', fieldName: 'Phone'}
    ];

    //more columns here...

    this.columns.push({ type: 'button-icon', typeAttributes: { 
        iconName: 'action:preview', name: 'preview', alternativeText: 'Preview Record', class: { fieldName: `format` } } 
    });
}

handleRowAction(event) {
    if (event.detail.action.name === 'preview') {
        //color the button that was clicked
    }
}

HTML:

<template>
<lightning-datatable key-field="id" 
                     data-id='datatable'
                     data={recordsDisplayed} 
                     columns={columns} 
                     onrowaction={handleRowAction}>
</lightning-datatable>
2

1 Answer 1

1

You need to set the row's attribute to change just one button.

Your typeAttributes needs to be changed to:

 iconName: 'action:preview', name: 'preview', alternativeText: 'Preview Record', variant: { fieldName: `format` } } 

To get there properly, first find the element:

let actionRow = this.recordsDisplayed[this.recordsDisplayed.indexOf(event.detail.row)];

... or ...

let actionRow => this.recordsDisplayed.find(row => event.detail.row.Id === row.Id);

Then set the value for the field you mapped for the variant:

actionRow.format = 'brand';

Finally, make sure you set @track on recordsDisplayed, or copy the array so that LWC can determine a change needs to be rendered:

@track displayedRecords;

... or ...

this.displayedRecords = [...this.displayedRecords];

Putting it all together:

handleRowAction(event) {
  if(event.detail.action === 'preview') {
    let actionRow = this.displayedRows.find(
      (row) => row.Id === event.detail.row.Id
    );
    actionRow.format = 'brand';
    this.displayedRows = [...this.displayedRows];
  }
}
1
  • Thanks @sfdcfox for the detailed answer.
    – Cap10
    Jun 8, 2021 at 6:30

You must log in to answer this question.

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