How to add a onclick action on a specific column in a standard datatable component

datatablejslightninglightning-datatablelightning-web-components

How to have on click action for specific column in data table in lwc.
consder this as example, js:

columns = [ {label: 'Opportunity name', fieldName: 'opportunityName', type: 'text'},
{label: 'Confidence', fieldName: 'confidence', type: 'percent', cellAttributes: { iconName: { fieldName: 'trendIcon' }, iconPosition: 'right' }} ];

I want to open a modal by clicking on "Confidence". if I give onclick in html, for example:

<lightning-datatable data={data} columns={columns}" onclick={openmodal}></lightning-datatable>

In this case modal will open wherever I click on data-table, instead of specific column.

Anyone knows any solution for this?

Best Answer

Implement a custom data type with your html executing modal on click

Recently a new feature was released which allows to define custom data types in standard lightning:datatable component.

Create a LWC component customTable with the following JS

import LightningDatatable from 'lightning/datatable';
import clickModal from './clickModal.html';
 
export default class CustomTable extends LightningDatatable {
    static customTypes = {
        clickModal: {
            template: clickModal,
            standardCellLayout: true
        }
    }
}

Create in the customTable folder additional file clickModal.html

<template>
    <lightning-formatted-text value={value} onclick={openModal}></lightning-formatted-text>
</template>

Use overridden version of Lightning Data Table

<c-custom-table ...> 

Set the column type to clickModal

columns = [ {
    label: 'Opportunity name', fieldName: 'opportunityName', type: 'text'}, {
    label: 'Confidence', fieldName: 'confidence', type: 'clickModal', cellAttributes: {
        iconName: { fieldName: 'trendIcon' },
        iconPosition: 'right'
    }
} ];