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:

2 comments

  1. This article provides a clear example of how data can flow between Lightning Web Components using the parent-child relationship. The @api decorator is particularly important because it exposes a property as part of the child component's public interface, while the parent can provide the value through the component markup. This makes Javascript Online Course concepts such as properties, component interaction, and data binding useful when understanding the JavaScript side of LWC development.

    ReplyDelete
  2. The message={message} example also demonstrates how a parent component can pass dynamic values into a child rather than hard-coding the information inside the child itself. This approach provides a simple foundation for reusable components, where the same child component can receive different values from different parents. Developers strengthening these concepts through Javascript Online Training can build a stronger understanding of how JavaScript properties and component communication work together in LWC.

    ReplyDelete