Sunday, September 22, 2024

What are events in LWC? How Communications happens in LWC?

In Lightning Web Components (LWC), events are used for communication between components, particularly for passing information or triggering actions. 

In Lightning Web Components (LWC), there are three primary approaches for communication between components using events:

  1. Parent-to-Child Communication: This allows a parent component to pass data or trigger actions in a child component via public properties or methods.

  2. Child-to-Parent Communication (Custom Events): Child components can send data or trigger actions in their parent component by dispatching custom events.

  3. Publish-Subscribe Pattern (LMS): This pattern enables communication between two components that do not have a direct parent-child relationship, using the Lightning Message Service (LMS) to broadcast and subscribe to events across the application. 

Event Phase in LWC:

Lightning web components use only the bubbling phase. Dispatching events or adding listeners to the capture phase isn't supported. Simply think of the event’s path as starting with your component and then moving to its parent, and then grandparent, and so on.

Parent-to-Child Communication:

In Lightning Web Components, data can be passed from a parent to a child component using the following two methods:

1. Public Properties: These are reactive properties defined in the child component that the parent component can set directly.


2. Public Methods: These are methods in the child component that the parent component can invoke to pass data or trigger specific behavior.


Child-to-Parent Communication (Custom Events)

Child to Parent communication is achieved by triggering custom event from child LWC and handling it parent LWC as explained in blog: https://www.sfdc-lightning.com/2020/01/how-to-pass-data-from-child-component-to-parent-component-in-lightning-web-component.html

We will see the use of Publish-Subscribe Pattern (LMS) in our next blog.

No comments:

Post a Comment