type: “button” should be used in columns attribute to display buttons in LWC lighting datatable.
Sample Code:
HTML:
<template>
<lightning-card title = "Search Accounts" icon-name = "custom:custom63">
<div class = "slds-m-around_medium">
<lightning-input type = "search" onchange = {handleKeyChange} class = "slds-m-bottom_small" label = "Search" >
</lightning-input>
<template if:true = {accounts}>
<div style="height: 300px;">
<lightning-datatable key-field="Id"
data={accounts}
columns={columns}
hide-checkbox-column="true"
show-row-number-column="true"
onrowaction={callRowAction}>
</lightning-datatable>
</div>
</template>
<template if:true = {error}>
{error}>
</template>
</div>
</lightning-card>
</template>
JAVASCRIPT:
import { LightningElement } from 'lwc';
import fetchAccounts from '@salesforce/apex/AccountController.fetchAccounts';
import { NavigationMixin } from 'lightning/navigation';
const COLUMNS = [
{ label: 'Id', fieldName: 'Id' },
{ label: 'Name', fieldName: 'Name' },
{ label: 'Industry', fieldName: 'Industry' },
{ type: "button", typeAttributes: {
label: 'View',
name: 'View',
title: 'View',
disabled: false,
value: 'view',
iconPosition: 'left'
} },
{ type: "button", typeAttributes: {
label: 'Edit',
name: 'Edit',
title: 'Edit',
disabled: false,
value: 'edit',
iconPosition: 'left'
} }
];
export default class accountSearchLWC extends NavigationMixin(LightningElement) {
accounts;
error;
columns = COLUMNS;
handleKeyChange( event ) {
const searchKey = event.target.value;
if ( searchKey ) {
fetchAccounts( { searchKey } )
.then(result => {
this.accounts = result;
})
.catch(error => {
this.error = error;
});
} else
this.accounts = undefined;
}
callRowAction( event ) {
const recId = event.detail.row.Id;
const actionName = event.detail.action.name;
if ( actionName === 'Edit' ) {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: recId,
objectApiName: 'Account',
actionName: 'edit'
}
})
} else if ( actionName === 'View') {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: recId,
objectApiName: 'Account',
actionName: 'view'
}
})
}
}
}
JS-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__Tab</target>
</targets>
</LightningComponentBundle>
Apex Class:
public with sharing class AccountController {
@AuraEnabled( cacheable = true )
public static List< Account > fetchAccounts( String searchKey ) {
String strKey = '%' + searchKey + '%';
return [
SELECT Id, Name, Industry
FROM Account
WHERE Name LIKE: strKey LIMIT 10
];
}
}
Output: