[SalesForce] Hook up a Modal to a button in a row LWC Datatable

How can I hook up a modal dialog when user click the column type button (Add) in a DataTable (see screenshot). The rows are generated dynamically in the datatable component. The modal will have some items (checkboxes) selected. I will then need to display the selection in a second datatable (not shown). Is there any example code on how to.

// The constants for the datatable
    const columns = [
    {label: 'column1', fieldName: 'column1', type: 'text'},
    {label: 'column2', fieldName: 'column2', type: 'currency', typeAttributes:
        { currencyCode: 'USD' }},
    {label: 'column3', fieldName: 'column3', type: 'currency', typeAttributes: { currencyCode: 'USD', step: '0.01'}},
    {label: 'column4', fieldName: 'column4', type: 'number'},
    {type: 'button', typeAttributes: { label: 'Add', title: 'Add', name: 'add', iconPosition: 'center', variant: 'brand'}},
];

const data = [{
    id: 'a',
    column1: 'product 1',
    column2: 35,
    column3: 35.00,
    column4: 25,

},
//and the class has
export default class myclass extends LightningElement {
    options = [
        { label: 'option1', value: 'option1' },
        { label: 'option2', value: 'option2' },
        { label: 'option3', value: 'option3' }
    ];
    value = [];

    @track hide = true;
    //TODO: check
    @track showModal = false;

    data = data;
    columns = columns;


    handleShowModalClick() {
        this.showModal = true;
        const selectedEvent = new CustomEvent('showmodalclick');
        this.dispatchEvent(selectedEvent);
    }

enter image description here

Best Answer

You need to handle the row action event on lightning-datatable. like

<lightning-datatable key-field="id" data={data} columns={columns} onrowaction={handleRowAction} ...>

As you have mentioned the name add in the typeAttributes of the button column, you can handle that action like below.

handleRowAction(event) {
    if (event.detail.action.name === 'add') {
        // write your code to open the modal
    }
    // if you have multiple actions you can use the switch case.
}

For more details, check out this git repo: Add-Delete-Row-in-Lightning-Datatable-Lwc

Related Topic