Wednesday, December 7, 2022

Communication in LWC Components

 In LWC we have 2 types of Communication as given below

Communication Types

So, in this blog, we are going to cover:

  • Parent to Child Communication.
  • Child to Parent Communication.

Parent to Child Communication

As the name suggests, Parent to Child communication happens between two components when the parent component contains the child component tag in its HTML file and passes data to the child component. To pass data to the child component, we need to define a variable with @api decorator in the child component to be public and accessed from the parent component.

Note: @api decorator used to define public property, which is reactive.

An Example for Better Understanding

Here we defined a variable getValueFromParent using the @api decorator in child and used it in the HTML template to display its value in the child component.

childcmp.js

childcmp.html

Now moving towards the parent component, declare one variable in the parent component to pass it to the child component. Here we created a value variable and assigned a string literal to it. To pass the value to the child component, add the child component’s tag to the parent HTML template and assign the value to the child’s property as an attribute.

parentcmp.js

parentcmp.html