There are few scenarios where we need to pass property/values from parent component to child component in LWC. There are different ways to achieve this:
- Using @api decorator (public property)
The @api decorator in the child component makes property as
public, which can be utilised by parent component to update it. So whenever you add child component in parent component, then specify child public property as an attribute and pass the value from parent component property.
For example, Child component contains public property "passedUrl" with @api decorator
-----------childComponent.html--------------------
<template> <div style="background-color:#b2b689;border-style: solid;"> <b>Child component</b> <p>URL passed from parent-<b>{passedUrl}</b></p> </div> </template>
--------childComponent.js---------------------
import { LightningElement,api} from 'lwc'; export default class SkChildComponent extends LightningElement { @api passedUrl; }
Now if you have to pass value to "passedUrl" property from parent component then just specify attribute as property name and pass any value from parent component property.
--------parentComponent.html---------------------
<template> <lightning-card title="Communicate from Parent to Child"> <div style="background-color:#E6E6FA;border-style: "> <b>This is parent Component</b> <c-child-component passed-url={selResourceURL} > </c-child-component> </div> </lightning-card> </template>
--------parentComponent.js---------------------
import { LightningElement,track } from 'lwc'; export default class SkParentContainerCmp extends LightningElement { @track selResourceURL='https://www.sfdcstuff.com/'; }
- Using getter setter property in child component
--------childComponent.js---------------------
import { LightningElement,api,track } from 'lwc'; export default class SkChildComponent extends LightningElement { @track _userInputNumber; @api get userInputNumber(){ return this._userInputNumber; } set userInputNumber(value){ //write your logic to set any property this._userInputNumber=value; } }
- By accessing child function from parent component
@api increaseCounter(){ //your logic }
Now from parent component you can access this function by using below syntax:
this.template.querySelector('c-child-component').increaseCounter();
I have created parent and child component to explain how this communication from parent to child component happen. Please find below complete code snippet and components snapshot:
Hope this will Help!!