salesforceapexlwc

I don't know how to add a delete button to Lightning-datatable


Here is my Lightning-datatable:

enter image description here

Tell me how to make Delete buttons (in the Action column) and how to delete the line on this button when you click on the Delete button


Solution

  • Here is an example

    <lightning-datatable
        data={data}
        columns={columns}
        key-field="id"
        actions={[
            { label: 'Delete', name: 'delete' }
        ]}
        onrowaction={handleRowAction}
    ></lightning-datatable>
    

    When the action is triggered on a row in the table, the onrowaction event will be fired, and the event handler specified by the onrowaction attribute (in this case, handleRowAction) will be called.

    In your event handler:

    function handleRowAction(event) {
        const actionName = event.detail.action.name;
        const row = event.detail.row;
        switch (actionName) {
            case 'delete':
                deleteRecord(row);
                break;
            default:
        }
    }
    
    function deleteRecord(row) {
        // Implement logic to delete the record associated with the row
    }