Hi,
I would like to add different buttons in lwc lightning datatable based on column value.
for example:
if status column value is 'Inactive' -Edit Button
if status column value is 'Active' - No button
Anyone please help?
In your LWC JavaScript file, define a new property in the data object to store the button type for each row of the datatable.
data() {
return {
columns: [
{ label: 'Name', fieldName: 'name' },
{ label: 'Status', fieldName: 'status' },
],
data: [],
buttonType: [],
};
}
In your LWC JavaScript file, iterate through the data in the connectedCallback lifecycle method and set the button type for each row based on the status column value.
connectedCallback() {
// fetch data from an Apex method
this.data = [
{ name: 'John', status: 'Inactive' },
{ name: 'Jane', status: 'Active' },
];
for (let i = 0; i < this.data.length; i++) {
if (this.data[i].status === 'Inactive') {
this.buttonType[i] = 'Edit';
} else if (this.data[i].status === 'Active') {
this.buttonType[i] = 'NoButton';
}
}
}
In your LWC HTML file, use the template iteration to create a new column for the buttons and use the buttonType property to determine which button to render for each row.
<template>
<lightning-datatable key-field="id" data={data} columns={columns}>
<template if:true={buttonType.length > 0}>
<template for:each={data} for:item="row">
<template for:each={buttonType} for:item="type">
<template if:true={row.status === type.status}>
<template if:true={type.buttonType === 'Edit'}>
<lightning-button label="Edit" slot="action" onclick={handleEdit}></lightning-button>
</template>
<template if:true={type.buttonType === 'NoButton'}>
<lightning-button label="NoButton" slot="action" onclick={handleNoButton} disabled></lightning-button>
</template>
</template>
</template>
</template>
</template>
</lightning-datatable>
</template>