Communicating from parent lightning web component to child lightning web component

It is easy to communicate/send data from a parent lightning web component to a child lwc component. You can define a variable in the child lwc component javascript file, annotated it with @api annotation and finally pass value from parent component to the child component by using this variable name.

Example

1) Create an lwc component with name childLWCComponent


2) Create an lwc component with name parentLWCComponent

If you surface the parent component in lightning experience, it will looks like

parent to child lwc communication

Explanation

Here childLWCComponent has a javascript variable childVariable annotated with @api annotation. Parent component can pass value using this attribute name. But please note that camel case variable names in child component is converted to kebab case in parent component.

Use Cases

This is the most common form of communication/exchange of data between lwc components. Usually complex lightning apps are built as a combination of multiple child lwc components. ie a parent lwc component contining multiple child lwc components. This parent component will retain data that is needed by all child components and sends it to child components using variables defined in child component using @api annotation.


No comments:

Post a Comment