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
<template> | |
Value received from parent lwc component to child lwc component ==> <b>{childVariable}</b> | |
</template> |
import { LightningElement, api } from 'lwc'; | |
export default class ChildLWCComponent extends LightningElement { | |
@api childVariable; | |
} |
2) Create an lwc component with name parentLWCComponent
<template> | |
<!-- Notice that the uppercase characters in child component name needs to be replaced with - character --> | |
<c-child-l-w-c-component child-variable="Value sent from Parent"></c-child-l-w-c-component> | |
<c-child-l-w-c-component child-variable={dynamicVariable}></c-child-l-w-c-component> | |
</template> |
import { LightningElement } from 'lwc'; | |
export default class ParentLWCComponent extends LightningElement { | |
dynamicVariable = 'Dynamic value from Parent'; | |
} |
If you surface the parent component in lightning experience, it will looks like

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