Passing parameters between lightning LWC components

11:36 AM

There 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:

    1. Define a property in the parent component's JavaScript file.
    2. Mark the property with the @api decorator to make it accessible by the child component.
    3. Assign a value to the property and pass it down to the child component using the component tag.
  • Child Component:

    1. Import the parent component.
    2. Access the public property using the parent component's tag followed by a dot notation (e.g., parentComponentName.propertyName).
    3. 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:

    1. Create a new message channel using new MessageContext(this).
    2. Use the publish method of the message channel to send a message with data.
  • Subscriber Component:

    1. Subscribe to the message channel using subscribe method.
    2. Define a callback function to receive messages and handle the data.

Here are some resources for further learning:

0 comments