Sample Code:
Apex Class:
public with sharing class AccountController {
@AuraEnabled( cacheable = true )
public static List< Account > fetchAccounts() {
return [ SELECT Id, Name, Industry, AccountNumber
FROM Account
LIMIT 10 ];
}
}
HTML:
<template>
<div class="slds-box slds-theme--default">
<template if:true = {records}>
<div style = "height: 300px;">
<table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_striped">
<tr>
<th scope = "col">Name</th>
<th scope = "col">Industry</th>
<th scope = "col">Account Number</th>
</tr>
<template iterator:it = {records}>
<tr key = {it.value.Id}>
<td><a href="#" data-record-id={it.value.Id} onclick={viewAccount}>{it.value.Name}</a></td>
<td>{it.value.Industry}</td>
<td>{it.value.AccountNumber}</td>
</tr>
</template>
</table>
</div>
</template>
<template if:true = {error}>
{error}>
</template>
</div>
</template>
JavaScript:
import { LightningElement, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/AccountController.fetchAccounts';
import { NavigationMixin } from 'lightning/navigation';
export default class Sample extends NavigationMixin( LightningElement ) {
records;
error;
@wire( fetchAccounts )
wiredAccount( { error, data } ) {
if (data) {
this.records = data;
this.error = undefined;
} else if ( error ) {
this.error = error;
this.records = undefined;
}
}
viewAccount( event ) {
let rowId = event.target.dataset.recordId;
console.log( 'Record Id is ' + JSON.stringify( rowId ) );
event.preventDefault();
event.stopPropagation();
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: rowId,
objectApiName: 'Account',
actionName: 'view'
}
});
}
}
Output: