Pass value from child lightning component to parent lightning component using Dispatch Event: LWC
Parent Lightning Component
parentComponent.html
parentComponent.js
parentComponent.meta
childComponent.html
childComponent.js
PullAccount.cls
parentComponent.html
<template>
<lightning-card>
<div class="slds-p-around-medium">
{selectedAccountId}
<template for:each={accountsList} for:item="accountRecord" >
<c-child-component account={accountRecord} key={accountRecord.Id} onobjectlistitemselected={handleObjectListItemSelected}></c-child-component>
</template>
</div>
</lightning-card>
</template>
parentComponent.js
import { LightningElement, wire, track } from 'lwc';
import getAccountList from '@salesforce/apex/PullAccount.seacrhAccount';
export default class ParentComponent extends LightningElement {
@track accountsList;
@track error;
searchKey = *****ACCOUNT RECORD ID*****;
@track selectedAccountId;
@wire(getAccountList, { accountRecordId: '$searchKey' })
wiredAccounts({ error, data }) {
if (data) {
this.accountsList = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.accountsList = undefined;
}
}
handleKeyChange(event) {
window.clearTimeout(this.delayTimeout);
const searchKey = event.target.value;
this.searchKey = searchKey;
}
handleObjectListItemSelected(event) {
console.log(event.detail.recordaction+'=========='+event.detail.recordId);
}
}
parentComponent.meta
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>48.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
childComponent.html
<template>
<lightning-input class="cb" type="checkbox" label="my checkbox" onchange={onChecboxChange}></lightning-input> {account.Name} {isSelected}
</template>
childComponent.js
import { LightningElement, api , track} from 'lwc';
export default class ChildComponent extends LightningElement {
@api account;
@track isSelected = false;
onChecboxChange(event) {
this.isSelected = event.target.checked;
this.dispatchEvent(
new CustomEvent('objectlistitemselected',{
detail: {recordId:this.account.Id, recordaction:event.target.checked}
})
);
}
}
PullAccount.cls
public class PullAccount {
@AuraEnabled(Cacheable=true)
public static List<Account> seacrhAccount(String accountRecordId) {
//return [SELECT Id, Name FROM Account WHERE Id =: accountRecordId];
return [SELECT Id, Name FROM Account LIMIT 5];
}
}
Comments
Post a Comment