Passing parameters between lightning LWC components
11:36 AMThere are two main ways to pass parameters between LWC components in Salesforce:
1. Using Public Properties with the @api
decorator:
This method is ideal when there's a parent-child relationship between the components. Here's how it works:
Parent Component:
- Define a property in the parent component's JavaScript file.
- Mark the property with the
@api
decorator to make it accessible by the child component. - Assign a value to the property and pass it down to the child component using the component tag.
Child Component:
- Import the parent component.
- Access the public property using the parent component's tag followed by a dot notation (e.g.,
parentComponentName.propertyName
). - Use the received value in the child component's logic or template.
Here's an example:
Parent Component (parent.js):
Parent Component (parent.html):
Child Component (child.js):
2. Using Lightning Message Service (LMS) for Non-Parent-Child Communication:
This method is useful when the components don't have a direct parent-child relationship. LMS provides a pub/sub mechanism for components to communicate with each other.
Publisher Component:
- Create a new message channel using
new MessageContext(this)
. - Use the
publish
method of the message channel to send a message with data.
- Create a new message channel using
Subscriber Component:
- Subscribe to the message channel using
subscribe
method. - Define a callback function to receive messages and handle the data.
- Subscribe to the message channel using
Here are some resources for further learning:
- Salesforce Documentation on LWC Properties: https://developer.salesforce.com/docs/platform/lwc/guide/js-props-intro.html
- Salesforce Documentation on Lightning Message Service: https://developer.salesforce.com/docs/component-library/bundle/lightning-message-service
0 comments