Dispatch a Custom Event From a Custom Data Type

The lightning-datatable component fires several custom events, including the rowselection event when a row is selected. For more information on the custom events available for lightning-datatable, see the lightning-datatable reference documentation.

If these custom events don’t meet your requirements, you can dispatch your own custom event and handle it from your parent component.

This documentation uses the term lightning-datatable component and datatable interchangeably.

Note

Example: Navigate to a Record with a Custom Data Type 

Here’s an example that navigates to a record when a custom data type is clicked. The datatable loads a Contact Picture column using a custom data type.

This example modifies the customDataTypes component in the lwc-recipes GitHub repo.

Tip

Clicking a contact’s photo redirects you to the corresponding contact record page using the navigation service.

1customDataTypes
2   ├──customDataTypes.html
3   ├──customDataTypes.js
4   ├──customDataTypes.js-meta.xml
5   └──customPicture.html

The customDataTypes.js file imports and defines the customPicture data type within the same folder. To make the record ID available when the photo is clicked, the custom data type includes the recordId type attribute.

customDataTypes.js
1import LightningDatatable from "lightning/datatable";
2import customPicture from "./customPicture.html";
3export default class CustomDataTypes extends LightningDatatable {
4  static customTypes = {
5    customPictureType: {
6      template: customPicture,
7      standardCellLayout: true,
8      typeAttributes: ["pictureUrl", "recordId"],
9    },
10    // Other Custom Types
11  };
12}

The customPicture template passes in the pictureUrl and recordId type attributes to the c-custom-pic child component, which is a new component you can create on your own that’s not part of the lwc-recipes repo.

customPicture.html
1<template>
2  <c-custom-pic picture-url={typeAttributes.pictureUrl} record-id={typeAttributes.recordId}>
3  </c-custom-pic>
4</template>

The c-custom-pic component includes a click handler. It displays an image based on the pictureUrl value passed in to the custom data type.

customPic.html
1<template>
2  <img
3  src={pictureUrl}
4  class="slds-avatar slds-avatar_circle slds-avatar_large"
5  alt="Profile photo"
6  title="Click photo to edit contact"
7  onclick={handleClick}
8  />
9</template>

The click handler dispatches a clicked custom event with the detail property.

customPic.js
1import { LightningElement, api } from 'lwc';
2
3export default class CustomPic extends LightningElement {
4
5  @api pictureUrl;
6  @api recordId;
7
8  handleClick() {
9    const photoClickEvent = new CustomEvent("photoclick", {
10        composed: true,
11        bubbles: true,
12        cancelable: true,
13        detail: {
14          pictureUrl: this.pictureUrl,
15          recordId: this.recordId
16        },
17    });
18    this.dispatchEvent(photoClickEvent);
19  }
20}

The datatableCustomDataType parent component listens to and handles the photoclick custom event.

datatableCustomDataType.html
1<template>
2    <lightning-card
3        title="Datatable Custom Data Type"
4        icon-name="custom:custom62"
5    >
6        <c-custom-data-types
7            key-field="Id"
8            data={data}
9            show-row-number-column
10            column-widths-mode="auto"
11            columns={columns}
12            onphotoclick={handlePhotoClick}>
13          </c-custom-data-types>
14      </lightning-card>
15</template>

The parent component imports the lightning/navigation module so it can navigate to a record edit page.

datatableCustomDataType.js
1import { LightningElement, wire } from 'lwc';
2import { NavigationMixin } from "lightning/navigation";
3
4import getContacts from '@salesforce/apex/ContactController.getContactList';
5
6const COLS = [
7    { label: 'First Name', fieldName: 'FirstName' },
8    { label: 'Last Name', fieldName: 'LastName' },
9    { label: 'Title', fieldName: 'Title' },
10    { label: 'Phone', fieldName: 'Phone', type: 'phone'},
11    { label: 'Email', fieldName: 'Email', type: 'email' },
12    {
13        label: 'Contact Picture',
14        type: 'customPictureType',
15        typeAttributes: {
16            pictureUrl: { fieldName: 'Picture__c' },
17            recordId: { fieldName: 'Id'}
18        },
19    }
20];
21export default class DatatableCustomDataType extends NavigationMixin(LightningElement) {
22    columns = COLS;
23    data = [];
24
25    @wire(getContacts)
26    contacts(result) {
27        if (result.data) {
28            this.data = result.data;
29            this.error = undefined;
30
31        } else if (result.error) {
32            this.error = result.error;
33            this.data = undefined;
34        }
35    }
36
37    handlePhotoClick(e) {
38        const { pictureUrl, recordId } = e.detail;
39
40        // View the contact record
41        this[NavigationMixin.Navigate]({
42            type: "standard__recordPage",
43            attributes: {
44            recordId: recordId,
45            actionName: "view",
46            },
47        });
48    }
49}

The ContactController.cls Apex class returns a list of contacts.

ContactController.cls
1public with sharing class ContactController {
2    @AuraEnabled(cacheable=true)
3    public static List<Contact> getContactList() {
4        return [
5            SELECT
6                Id,
7                Name,
8                FirstName,
9                LastName,
10                Title,
11                Phone,
12                Email,
13                Picture__c
14            FROM Contact
15            WHERE Picture__c != NULL
16            WITH USER_MODE
17            LIMIT 10
18        ];
19    }
20}

Dispatch a Custom Event via a Slot 

If you dispatch a custom event on a custom data type via the customdatatypes slot, you can handle the custom event on the lightning-datatable component. For example, add the onphotoclick handler like this.

datatableCustomDataType.html
1<lightning-datatable
2    key-field="Id"
3    data={contacts.data}
4    show-row-number-column
5    column-widths-mode="auto"
6    columns={columns}
7    onphotoclick={handlePhotoClick}>
8    <template if:true={showCustomTypes}>
9        <c-custom-data-types slot="customdatatypes"></c-custom-data-types>
10    </template>
11</lightning-datatable>

For more information, see Pass in Custom Data Types Using a Slot.

See Also

Release Preview

This release is in preview. Features described here don't become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can't guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.