Is it possible to return an entire object (not just a single field) from a for:each Template in LWC?
Specifically, I'm not sure why I can't access the object in the same way I can a normal object in object.key notation. See my test below where I hardcoded an object which is output to the console just fine, but is not output to the console when I assign the object pulled from 'event.target.dataset.account'
getAccountList.html
<template>
<lightning-card title="Get Account List">
<lightning-button label="Get Accounts" onclick={handleGetAccounts}></lightning-button>
<template for:each={accList.data} for:item="account">
<lightning-card title={account.Name} icon-name="standard:account" key={account.Id}>
<lightning-button label="Select Account" onclick={handleSelectAccount}
data-account={account} data-account-id={account.Id} data-account-name={account.Name}></lightning-button>
</lightning-card>
</template>
</lightning-card>
html: v.1.7
js: {version}
</template>
getAccountList.js
import { LightningElement, wire } from 'lwc';
import getAccList from '@salesforce/apex/getAccountListController.getAccList';
export default class GetAccountList extends LightningElement {
version='v.1.7';
selAccount;
@wire(getAccList) accList;
handleGetAccounts(event){
console.log('start handleGetAccounts');
console.log('accList: ',JSON.stringify(this.accList));
console.log('end handleGetAccounts');
}
handleSelectAccount(event){
console.log('start handleSelectAccount');
//Test getting simple object
this.selAccount = {Id: 1, Name: 'David'};
console.log('JSON.stringify(this.selAccount)', JSON.stringify(this.selAccount));
console.log('this.selAccount.Id', this.selAccount.Id);
//Cannot get entire object
this.selAccount = event.target.dataset.account;
console.log('JSON.stringify(this.selAccount)',JSON.stringify(this.selAccount));
console.log('this.selAccount.Id',this.selAccount.Id);
//Get Fields Using Dataset
console.log('event.currentTarget.dataset.accountId',event.currentTarget.dataset.accountId);
console.log('event.currentTarget.dataset.accountName',event.currentTarget.dataset.accountName);
//Get Fields Using getAttribute
console.log('event.target.getAttribute(\'data-account-id\')',event.target.getAttribute('data-account-id'));
console.log('event.target.getAttribute(\'data-account-name\')',event.target.getAttribute('data-account-name'));
}
}
