1

I need help with LWC.

<template>
<div class="slds-card__body">
    <lightning-datatable
        key-field="Id"
        data={tableData}
        columns={columns}>
    </lightning-datatable>
</div>
So in columns i have one with URL type. And i need to have an event or something to get Id of row when user clicks on that URL field. so how can i do that? please help.
4

1 Answer 1

-1

Following the above comment , To get the Id of the row when the user clicks on the URL field in the lightning-datatable, you can use the onrowaction event in the lightning-datatable.

Here's an example of how you can modify your code to achieve this:

<template>
<div class="slds-card__body">
    <lightning-datatable
        key-field="Id"
        data={tableData}
        columns={columns}
        onrowaction={handleRowAction}>
    </lightning-datatable>
</div>

In the handleRowAction method, you can access the selected row by accessing the detail property of the event and then retrieve the Id of that row. You can then use this Id as needed. In the below example, I have simply logged it to the console for demonstration purposes.

<script>
import { LightningElement, api } from 'lwc';

export default class MyComponent extends LightningElement {
    @api tableData;
    columns = [
        //... your other columns
        { 
            label: 'URL', 
            fieldName: 'URL_Field__c', 
            type: 'url', 
            typeAttributes: { 
                label: { fieldName: 'Name' },
                target: '_blank' 
            }
        }
    ];

    handleRowAction(event) {
        const row = event.detail.row;
        const rowId = row.Id;
        // Use the rowId as needed
        console.log('Row Id: ', rowId);
    }
}
</script>

I hope this helps!

1
  • I don't think this works. It opens the url and does not invoke the handleRowAction() method for me.
    – TehNrd
    Jan 14 at 20:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .