Hello friends, In this post you will find an example that shows, how you can pass data from parent component to child component in lwc. so let's get started,
Pass data from parent to child component in lwc
For this post, I am using account object data but you can use any salesforce object as per your choice and you have to create two lwc component to accomplish this task.
ParentChildHandler.apxc
public class ParentChildHandler {ChildComponent.html
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts(){
return [ SELECT Id, Name, Industry,NumberOfEmployees FROM Account order by Name asc LIMIT 10 ];
}
}
<template>ChildComponent,js
<lightning-record-view-form record-id={recId} object-api-name={sObjectName} density="compact">
<div class="slds-box">
<lightning-output-field field-name={accName}>
</lightning-output-field>
<lightning-output-field field-name={accIndustry}>
</lightning-output-field>
<lightning-output-field field-name={accNumberOfEmployees}>
</lightning-output-field>
</div>
</lightning-record-view-form>
</template>
import { LightningElement, api } from 'lwc';ChildComponent.js-meta.xml
export default class ChildComponent extends LightningElement {
@api recId;
@api sObjectName;
@api accName;
@api accIndustry;
@api accNumberOfEmployees;
}
<?xml version="1.0"?>ParentComponent.html
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
</LightningComponentBundle>
<template>ParentComponent.js
<div class="slds-theme--default">
<template for:each={accounts.data} for:item="acc">
<div key={acc.Id}>
<c-child-component rec-id={acc.Id} s-object-name="Account" acc-name="Name" acc-industry="Industry"
acc-number-of-employees="NumberOfEmployees">
</c-child-component>
</div>
</template>
</div>
</template>
import { LightningElement, wire } from 'lwc';ParentComponent.js-meta.xml
import getAccounts from '@salesforce/apex/ParentChildHandler.getAccounts';
export default class ParentComponent extends LightningElement {
accounts;
@wire(getAccounts) accounts;
}
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>51.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__Tab</target>
</targets>
</LightningComponentBundle>
Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.
0 Comments
Post a Comment