In this blog post, we will learn "How to pass data from parent component to child component in lightning web component".
import { LightningElement, api } from 'lwc';
Parent component can make use of the Public Property.
We can pass data from parent LWC to child LWC while calling the child LWC from parent LWC.
In child LWC we need to decorate properties with @api decorator as shown in below example.
Properties decorated with @api are public reactive properties. When we use the @api decorator, we must import it explicitly from lwc as shown below.
import { LightningElement, api } from 'lwc';
Parent component can make use of the Public Property.
childcompdemo.html
<template>
<div>
<p>
Hi, I am from child component HTML file.
</p>
<p>
<b>Message from parent comp is </b> : {messagefromparent}
</p>
<p>
<b>Name of parent comp is </b>: {parentcompname}
</p>
</div>
</template>
childcompdemo.js
import { LightningElement, api } from 'lwc';
export default class Childcompdemo extends LightningElement {
@api messagefromparent;
@api parentcompname;
}
parentcompdemo.html
<template>
<div>
Hi, I am from parent component HTML file.
<c-childcompdemo messagefromparent="Hi this message is from parent comp" parentcompname="parentcompdemo" ></c-childcompdemo>
</div>
</template>
parentcompdemo.js
//* eslint-disable no-alert */
import { LightningElement } from 'lwc';
export default class Parentcompdemo extends LightningElement {
}
lightningapp.app
<aura:application extends="force:slds">
<c:parentcompdemo></c:parentcompdemo>
</aura:application>
This comment has been removed by a blog administrator.
ReplyDelete